#!/opt/dosis2/bin/python3-venv

import os
import sys
import subprocess
import socket
import psycopg2
import xml.etree.ElementTree as ET

ONE_HOUR = 3600

SALT_MASTER = '3.14.193.40'
DOSIS_CONFIG = '/opt/dosis2/etc/custom/dosisConfig.xml'

def does_file_exist(file_path):
    return os.path.exists(file_path)

def get_dafe_tag():
    return socket.gethostname().upper().replace('-D', '-')

def get_customer_num(db_ip):
    try:
        conn = psycopg2.connect(f"dbname='dosis2' user='dsuper' host='{db_ip}' password='1$Dosis'")
        cur = conn.cursor()
        cur.execute("""
        SELECT site.site_settings.value as site_setting_value
        FROM site.site_settings
        LEFT JOIN site.site_setting_types ON (site.site_settings.setting_type_id = site.site_setting_types.id)
        WHERE site.site_setting_types.tag = 'CUSTOMER_NUMBER';
        """)
        row = cur.fetchone()
        return row[0]
    except psycopg2.OperationalError as err:
        logger.error(err)

def get_db_ip(file_path):
    root = ET.parse(file_path)
    return root.find("./section[@name='general']/property[@name='DBServer']/value").text

def run_command(command, timeout=None):
    result = {'command': command, 'success': False, 'stdout': '', 'stderr': ''}
    try:
        process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        output, error = process.communicate(timeout=timeout)
        result['stdout'] = output.decode('utf-8').strip()
        result['stderr'] = error.decode('utf-8').strip()
        result['success'] = process.returncode == 0
    except subprocess.TimeoutExpired as e:
        process.kill()
        result['stderr'] = f"Command '{command}' timed out after {timeout} seconds."
        logger.error(f"{result['stderr']}")
    except Exception as e:
        result['stderr'] = str(e)
        logger.error(f"{result['stderr']}")
    return result

def create_file_and_directory(file_path):
    directory = os.path.dirname(file_path)
    if not os.path.exists(directory):
        os.makedirs(directory)
    if not os.path.isfile(file_path):
        open(file_path, 'w').close()

def write_lines_to_file(file_path, lines):
    with open(file_path, 'w') as f:
        f.writelines(f"{line}\n" for line in lines)

if __name__ == '__main__':
    if does_file_exist('/etc/salt/minion'):
        sys.exit("Agent already installed.")

    db_ip = get_db_ip(DOSIS_CONFIG)
    customer_number = get_customer_num(db_ip)
    dafe_tag = get_dafe_tag()

    # create file to set salt transport
    transport_path = '/etc/salt/minion.d/transport.conf'
    create_file_and_directory(transport_path)
    transport_lines = ['transport: tcp']
    write_lines_to_file(transport_path, transport_lines)

    # -A to pass ip
    # -i to pass id
    install_agent_cmd = f"/usr/share/dosis2/bin/bootstrap-salt.sh -A {SALT_MASTER} -i {customer_number}-{dafe_tag}"
    result = run_command(install_agent_cmd, ONE_HOUR)
    result_msg = f"COMMAND: {result['command']}\nSUCCESS: {result['success']}\nSTDOUT: {result['stdout']}\nSTDERR: {result['stderr']}"
    sys.exit(result_msg)
