#!/usr/bin/env python
import os.path
import sys
import configobj
import common


def get_key(easy_env_path, section, key):
    easy_env_dir = os.path.dirname(easy_env_path)
    try:
        succ = common.get_lock(easy_env_dir, filename="easy_env.lock")
        if not succ:
            raise Exception("Get lock(easy_env.lock) error.")
        config = configobj.ConfigObj(easy_env_path)
        if section not in config or key not in config[section]:
            return config["DEFAULT"].get(key, None)
        return config[section][key]
    finally:
        common.release_lock(easy_env_dir, filename="easy_env.lock")


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

    current_path = os.path.dirname(os.path.abspath(__file__))
    section = sys.argv[1]
    key = sys.argv[2]

    easy_env_path = "{0}/../easy_env.ini".format(current_path)
    try:
        value = get_key(easy_env_path, section, key)
        if value is None:
            print "Key not found!"
            sys.exit(2)
        print value
    except Exception, e:
        print "Error: e={0}".format(e)
        sys.exit(3)
