#!/usr/bin/python

##########
#
# This script install ansible modules for manage Eltex ESR devices
# There are two modules: esr_command and esr_config
# For succesfully install you need properly installed Ansible software with version >= 2.7
#
# Eltex, 2019
#
##########

import os
import re
from distutils.dir_util import copy_tree
import shutil

MODULES_PATH = {
    "root": "",
    "doc_fragments": ""
}

def copy_files(files, src_dir, dest_dir):
    if not os.path.exists(dest_dir):
        print("Creating directory {}".format(dest_dir))
        os.mkdir(dest_dir)

    if type(files) is not list:
        files = [files]

    for file in files:
        src_file_path = os.path.join(src_dir, file)
        dest_file_path = os.path.join(dest_dir, file)
        if os.path.exists(src_file_path):
            if os.path.exists(dest_file_path):
                print("Overwriting {}".format(dest_file_path))
            else:
                print("Copying to {}".format(dest_file_path))
            shutil.copy(src_file_path, dest_file_path)

def check_ans_install():
    print("Checking Ansible installation...")
    if not os.system("which ansible"):
        return True
    return False

def get_ans_modules_path():
    cmd = "ansible --version | grep 'ansible python module location' | awk '{ print $6 }'"
    print("Checking Ansible modules path...")
    if os.system(cmd):
        return False
    MODULES_PATH["root"] = re.sub(r"^\s+|\n+$", '', os.popen(cmd).read())
    document_fragments_path_old = os.path.join(MODULES_PATH["root"], "utils", "module_docs_fragments")
    document_fragments_path_new = os.path.join(MODULES_PATH["root"], "plugins", "doc_fragments")
    if os.path.exists(document_fragments_path_new):
        MODULES_PATH["doc_fragments"] = document_fragments_path_new
    elif os.path.exists(document_fragments_path_old):
        MODULES_PATH["doc_fragments"] = document_fragments_path_old
    else:
        return False
    return True

def check_esr_modules():
    res = True
    print("Checking installed modules...")
    if os.system("ansible-doc -l | grep esr_config"):
        res = False
    if os.system("ansible-doc -l | grep esr_command"):
        res = False
    return res

def modules_install():
    print("Installing modules...")
    for root, subdirs, files in os.walk("./ansible"):
        relpath = os.path.relpath(root, "./ansible")
        copy_files(files, root, os.path.join(MODULES_PATH["root"], relpath))
    copy_files(os.listdir('./doc_fragments/'), './doc_fragments/', MODULES_PATH["doc_fragments"])


if not check_ans_install():
    print("Ansible software is not installed. Please install it")
    raise SystemExit(1)

if not get_ans_modules_path():
    print("Your Ansible software installation may be corrupted. Please reinstall it")
    raise SystemExit(1)

modules_install()

if not check_esr_modules():
    print("Modules are not installed. Please check your Ansible software installation, permissions for your user and retry")
    raise SystemExit(1)

print("Congratulations! Modules esr_command and esr_config are properly installed.\nPlease use `ansible-doc <module_name>` command for more information about usage")
