
import os
import logging


import yaml


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

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


def save():
    global config, data_path
    try:
        yaml.dump(config, file(data_path, "w"))
    except Exception as e:
        logging.warn("save config %s fail %s", data_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 scan_module_version(module):
    module_path = os.path.join(root_path, module)
    for filename in os.listdir(module_path):
        if os.path.isdir(os.path.join(module_path, filename)):
            return filename
    return False

def generate_default_config():
    global config
    config = {"modules": {}, "update":{"check_update":1, "last_path":"", "uuid":""}}

    modules = ["goagent", "launcher", "php_proxy"]
    for module in modules:
        version = scan_module_version(module)
        config["modules"][module] = {"auto_start":1, "current_version":version}

    config["modules"]["launcher"]["auto_start"] = 0 # this means auto start on system login

def recheck_module_path():
    need_save_config = False
    for module in config["modules"]:
        current_version = config["modules"][module]["current_version"]
        if os.path.isdir(os.path.join(root_path, module, current_version)):
            continue

        logging.info("module %s version %s not exist", module, current_version)
        current_version = scan_module_version(module)
        if not current_version:
            logging.error("recheck_module_path %s get version fail", module)
            continue

        config["modules"][module]["current_version"] = current_version
        logging.info("module %s auto upgrade to version %s", module, current_version)
        need_save_config = True

    return need_save_config

def main():
    if os.path.isfile(data_path):
        load()
        if recheck_module_path():
            save()
    else:
        generate_default_config()
    #config["tax"] = 260
    #save()
    #print yaml.dump(config)

main()

def test():
    load()
    val = get(["web_ui", "popup_webui"], 0)
    print val

def test2():
    set(["web_ui", "popup_webui"], 0)
    set(["web_ui", "popup"], 0)
    print config

if __name__ == "__main__":
    test2()
    #main()
    #a = eval('2*3')
    #eval("conf = {}")
@@ -1393,600 +1393,213 @@
 def 
-generate_default_config():%0A    global config%0A    config = %7B%22modules%22: %7B%7D, %22update%22:%7B%22check_update%22:1, %22last_path%22:%22%22, %22uuid%22:%22%22%7D%7D%0A%0A    modules = %5B%22goagent%22, %22launcher%22, %22php_proxy%22%5D%0A    for module in modules:%0A        version = scan_module_version(module)%0A        config%5B%22modules%22%5D%5Bmodule%5D = %7B%22auto_start%22:1, %22current_version%22:version%7D%0A%0A    config%5B%22modules%22%5D%5B%22launcher%22%5D%5B%22auto_start%22%5D = 0 # this means auto start on system login%0A%0Adef recheck_module_path():%0A    need_save_config = False%0A    for module in config%5B%22modules%22%5D:%0A        current_version = config%5B%22modules%22%5D%5Bmodule%5D%5B%22current_version%22%5D
+recheck_module_path():%0A    need_save_config = False%0A%0A    modules = %5B%22goagent%22, %22launcher%22, %22php_proxy%22%5D%0A    for module in modules:%0A        current_version = get(%5B%22modules%22, module, %22current_version%22%5D, %22_%22)
 %0A   
@@ -1966,22 +1966,20 @@
         
-config
+set(
 %5B%22module
@@ -1984,18 +1984,18 @@
 les%22
-%5D%5B
+, 
 module
-%5D%5B
+, 
 %22cur
@@ -2008,18 +2008,17 @@
 ersion%22%5D
- =
+,
  current
@@ -2025,16 +2025,17 @@
 _version
+)
 %0A       
@@ -2142,24 +2142,166 @@
 fig = True%0A%0A
+        if module != %22launcher%22 and get(%5B%22modules%22, module, %22auto_start%22%5D, -1) == -1:%0A            set(%5B%22modules%22, module, %22auto_start%22%5D, 1)%0A%0A%0A
     return n
@@ -2378,20 +2378,17 @@
  load()%0A
-    
+%0A
     if r
@@ -2421,128 +2421,14 @@
     
-    
 save()
-%0A    else:%0A        generate_default_config()%0A    #config%5B%22tax%22%5D = 260%0A    #save()%0A    #print yaml.dump(config)
 %0A%0Ama

fix bug: old user config update without php module