#!/usr/bin/env python
__author__ = 'hzp'

import sys
import os.path

import configobj
import common


def set_key(ini_path, section, key, value):
    ini_dir = os.path.dirname(ini_path)
    try:
        succ = common.get_lock(ini_dir, filename="easy_env.lock")
        if not succ:
            raise Exception("Get lock(easy_env.lock) error.")
        config = configobj.ConfigObj(ini_path)
        config.setdefault(section, {})
        config[section][key] = value
        config.write()
    except Exception, e:
        print u"Error: {0}".format(e)
        return False
    finally:
        common.release_lock(ini_dir, filename="easy_env.lock")
    return True


if __name__ == "__main__":
    if len(sys.argv) != 4:
        print "Usage: set_env.py section key value"
        sys.exit(1)

    section = sys.argv[1]
    key = sys.argv[2]
    value = sys.argv[3]

    current_path = os.path.dirname(os.path.abspath(__file__))
    easy_env_path = "{0}/../easy_env.ini".format(current_path)
    success = set_key(easy_env_path, section, key, value)
    if not success:
        sys.exit(2)
    print "Set ok."
