#!/usr/bin/env python

import os
import yaml
from xlog import getLogger
xlog = getLogger("launcher")


current_path = os.path.dirname(os.path.abspath(__file__))
root_path = os.path.abspath(os.path.join(current_path, os.pardir))
data_path = os.path.abspath(os.path.join(root_path, os.pardir, os.pardir, 'data'))
config_path = os.path.join(data_path, 'launcher', 'config.yaml')

config = {}


def load():
    global config, config_path
    try:
        config = yaml.load(open(config_path, 'r'))
        if config is None:
            config = {}
        # print(yaml.dump(config))
    except Exception as exc:
        print("Error in configuration file:", exc)


def save():
    global config, config_path
    try:
        yaml.dump(config, open(config_path, "w"))
    except Exception as e:
        xlog.warn("save config %s fail %s", config_path, e)


def get(path, default_val=""):
    global config
    try:
        value = default_val
        cmd = "config"
        for p in path:
            cmd += '["%s"]' % p
        value = eval(cmd)
        return value
    except:
        return default_val


def _set(m, k_list, v):
    k0 = k_list[0]
    if len(k_list) == 1:
        m[k0] = v
        return
    if k0 not in m:
        m[k0] = {}
    _set(m[k0], k_list[1:], v)


def set(path, val):
    global config
    _set(config, path, val)


def recheck_module_path():
    global config
    need_save_config = False

    xxnet_port = get(["modules", "gae_proxy", "LISTEN_PORT"], 8087)

    modules = ["gae_proxy", "launcher", "x_tunnel"]
    for module in modules:
        if module not in ["launcher"]:
            if not os.path.isdir(os.path.join(root_path, module)):
                del config[module]
                continue

            if get(["modules", module, "auto_start"], -1) == -1:
                set(["modules", module, "auto_start"], 1)

    if get(["modules", "launcher", "xxnet_port"], 0) == 0:
        set(["modules", "launcher", "xxnet_port"], xxnet_port)

    if get(["modules", "launcher", "control_port"], 0) == 0:
        set(["modules", "launcher", "control_port"], 8085)
        set(["modules", "launcher", "allow_remote_connect"], 0)

    if get(["modules", "launcher", "proxy"], 0) == 0:
        # default enable PAC on startup.
        set(["modules", "launcher", "proxy"], "pac")

    # if get(["modules", "gae_proxy", "control_port"], 0) == 0:
    #     set(["modules", "gae_proxy", "control_port"], 8084)

    if get(["no_mess_system"], 0) == 1 or os.getenv("XXNET_NO_MESS_SYSTEM","0") != "0" :
        xlog.debug("no_mess_system")
        os.environ["XXNET_NO_MESS_SYSTEM"] = "1"
        set(["no_mess_system"], 1)
        need_save_config = True

    return need_save_config


def init():
    if os.path.isfile(config_path):
        load()

    if recheck_module_path():
        save()


init()

@@ -382,16 +382,40 @@
 ig = %7B%7D%0A
+need_save_config = False
 %0A%0Adef lo
@@ -714,32 +714,60 @@
 ig, config_path%0A
+    global need_save_config%0A
     try:%0A       
@@ -809,16 +809,49 @@
 , %22w%22))%0A
+        need_save_config = False%0A
     exce
@@ -1402,31 +1402,87 @@
     
-_set(config, path, val)
+global need_save_config%0A    _set(config, path, val)%0A    need_save_config = True
 %0A%0A%0Ad
@@ -1528,37 +1528,8 @@
 nfig
-%0A    need_save_config = False
 %0A%0A  
@@ -2762,40 +2762,8 @@
 , 1)
-%0A        need_save_config = True
 %0A%0A  

fix config.py need_save_config