__author__ = 'hzp'
import logging
import sys
import os
import os.path
from datetime import datetime
import subprocess

current_path = os.path.dirname(os.path.abspath(__file__))
PROJECT_PATH = os.path.dirname(current_path)

if PROJECT_PATH not in sys.path:
    sys.path.append(PROJECT_PATH)

LOG_PATH = '/usr/local/easyops/deploy_init/log'
if not os.path.exists(LOG_PATH):
    os.makedirs(LOG_PATH)

today = datetime.now().strftime('%Y%m%d')
logger = logging.getLogger('mylog')
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter('[%(asctime)s %(funcName)s L%(lineno)d %(levelname)s] %(message)s'))
logger.addHandler(handler)
fhandler = logging.FileHandler('%s/deploy_init-%s.log' % (LOG_PATH, today))
fhandler.setFormatter(logging.Formatter('[%(asctime)s %(funcName)s L%(lineno)d %(levelname)s] %(message)s'))
logger.addHandler(fhandler)

import init_easy_env


def get_key(section, key):
    cmd = '{}/tools/get_env.py "{}" "{}"'.format(
        PROJECT_PATH, section, key
    )
    code, msg = exec_cmd([cmd], check_call=False)
    if code == 0:
        return msg.strip()
    return None


def exec_cmd(cmd, shell=True, check_call=True):
    sh = ' '.join(cmd)
    logger.debug(sh)
    if shell:
        cmd = sh

    proc = subprocess.Popen(args=cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell)
    out, err = proc.communicate()
    if out:
        logger.info(out)
    if err:
        logger.error(err)

    if check_call:
        if proc.returncode != 0:
            raise Exception('%s failed, %s' % (cmd, err))

    return proc.returncode, out or err


def generate_env_config():
    app2ips = init_easy_env.get_app_to_ips()
    cmdb_ip = app2ips["cmdb"][0]
    dc_ip = app2ips.get("dc_console", [""])[0]
    ens_root_ip = app2ips["ens_root"][0]
    server_ip = app2ips["gateway"][0]
    openapi_ip = app2ips.get("openapi", [""])[0]
    console_ip = app2ips["console-private"][0]

    org = get_key("common", "org")
    if org is None:
        raise Exception("get org failed")
    local_ip = get_key("common", "local_ip")
    if local_ip is None:
        raise Exception("get local_ip failed")
    inner_ip = get_key("common", "inner_ip")
    if inner_ip is None:
        raise Exception("get inner_ip failed")
    grafana_password = get_key("grafana", "password")
    if grafana_password is None:
        raise Exception("get grafana_password failed")
    with open("/usr/local/easyops/deploy_init/env.config", "w") as f:
        fcontent = "#!/bin/bash\n"\
                    "org={org}\n"\
                    "local_ip={local_ip}\n"\
                    "cmdb_ip={cmdb_ip}\n"\
                    "dc_ip={dc_ip}\n"\
                    "ens_root_ip={ens_root_ip}\n"\
                    "serverIp={server_ip}\n"\
                    "edition=\n"\
                    "inner_ip={inner_ip}\n"\
                    "NS_OPENAPI_IP={openapi_ip}\n"\
                    "grafana_password={grafana_password}\n"\
                    "console_url=http://{console_ip}\n".format(
            org=org, local_ip=local_ip, inner_ip=inner_ip, grafana_password=grafana_password,
            cmdb_ip=cmdb_ip, dc_ip=dc_ip, ens_root_ip=ens_root_ip, server_ip=server_ip,
            openapi_ip=openapi_ip, console_ip=console_ip
        )
        logger.info("env.config: {0}".format(fcontent))
        f.write(fcontent)

if __name__ == "__main__":
    generate_env_config()
