# -*- coding:utf-8 -*-
import os
from pprint import pprint


def init_env():
    if os.path.exists(r"/etc/profile.d/huansi.sh"):
        with open(r"/etc/profile.d/huansi.sh", "r") as f:
            setting = f.readlines()
        print("当前DB配置：\n{}\n".format(''.join([item.replace(r'\n', '') for item in setting])))

    while True:
        print('=========================设置DB=========================')
        print('如果想要退出，按住CTRL+C键然后再按一下Enter键即可退出，如果不知道，想象一下你要复制文本时候的按键')
        print('========================================================\n')

        HSCUSCODE = str(raw_input("请输入客户代号HSCUSCODE:"))
        print(HSCUSCODE)
        HSDB_HOST = str(raw_input("请输入数据库主机地址HSDB_HOST:"))
        print(HSDB_HOST)
        HSDB_PORT = str(raw_input("请输入数据库端口号HSDB_PORT(默认端口1433):"))
        print(HSDB_PORT)
        HSDB_USER = str(raw_input("请输入数据库用户HSDB_USER:"))
        print(HSDB_USER)
        HSDB_PASSWORD = str(raw_input("请输入数据库密码HSDB_PASSWORD:"))
        print(HSDB_PASSWORD)
        HSDB_PASSWORD = HSDB_PASSWORD.replace('$', '\$')
        HSDB_NAME = str(raw_input("请输入ERP数据库名称HSDB_NAME(默认HsGmtERP):"))
        if not HSDB_NAME:
            HSDB_NAME = 'HsGmtERP'
        print(HSDB_NAME)
        MESDB_NAME = str(raw_input("请输入MES数据库名称MESDB_NAME(默认HsGmtMES):"))
        if not MESDB_NAME:
            MESDB_NAME = 'HsGmtMES'
        print(MESDB_NAME)
        HSPASSWORD = "huansi.net"

        env = dict(HSCUSCODE=HSCUSCODE,
                   HSDB_HOST=HSDB_HOST,
                   HSDB_PORT=HSDB_PORT,
                   HSDB_USER=HSDB_USER,
                   HSDB_PASSWORD=HSDB_PASSWORD,
                   HSDB_NAME=HSDB_NAME,
                   MESDB_NAME=MESDB_NAME,
                   HSPASSWORD=HSPASSWORD
                   )
        pprint(env)
        flag = raw_input("请检查以上环境变量设置是否正确,确认请输入Y,输入其他,重新设置:")
        if str(flag).upper() == 'Y':
            with open("/etc/profile.d/huansi.sh", "w") as f:
                for k, v in env.items():
                    f.writelines("export {}={}\n".format(k, v))

            print('环境变量设置成功,目标文件为/etc/profile.d/huansi.sh')
            # 返回客户编号
            return HSCUSCODE
        elif flag == "N":
            continue
        else:
            continue


if __name__ == "__main__":
    init_env()
    print("环境变量设置结束")
