import sys,os,shutil
panelPath = os.getenv('BT_PANEL')
os.chdir(panelPath);
sys.path.append("class/")
import public,json

__path = os.getenv('BT_SETUP')


def CopyDir(sfile, dfile):
    """
    复制目录
    @get.sfile 源目录
    @get.dfile 目标目录
    """
    if not os.path.exists(sfile):
        return False
    if os.path.exists(dfile):
        return False
    import shutil
    public.copytree(sfile, dfile)
    return True


def install(name,version):

    _setup_path = '%s/%s' % (__path,"tomcat_server")
    if not os.path.exists(_setup_path): 
        os.makedirs(_setup_path)

    public.bt_print("正在智能选择节点...")
    downUrl = public.get_url()
    pluginUrl = downUrl + '/win/java/' + name + '/' + name + version + '.zip'
    tmp_path = __path + '/temp/%s%s.zip' % (name,version)

    print(pluginUrl,name,version)
    public.downloadFile(pluginUrl,tmp_path)
    if not os.path.exists(tmp_path): public.bt_print("文件下载失败，请检查网络原因.")

    if name.find("jdk") >=0:
        try:
            public.bt_print("正在解压文件...")
            import zipfile
            zip_file = zipfile.ZipFile(tmp_path)
            for names in zip_file.namelist():
                zip_file.extract(names,__path+'/jdk')

            zip_file.close()
        except :
            public.bt_print('文件被占用，更新前请先确保没有网站程序调用此版本的php程序.')
            return False
    else:
        try:
            public.bt_print("正在解压文件...")
            import zipfile
            zip_file = zipfile.ZipFile(tmp_path)
            for names in zip_file.namelist():
                zip_file.extract(names, _setup_path)
            zip_file.close()
        except:
            public.bt_print('文件被占用，更新前请先确保没有网站程序调用此版本的php程序.')
            return False

    if name.find("tomcat")>=0:   
        __jdk_data = {'tomcat7':['jdk1.7'],'tomcat8':['jdk1.8'],'tomcat9':['jdk1.8']}
        port2=51135+int(version)
        port=8367+int(version)
        __server_config=_setup_path+ '/' + name + version + '/conf/server.xml'
        ret = '''<Server port="{}" shutdown="SHUTDOWN">
            <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
            <Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener" />
            <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
            <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
            <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />
            <GlobalNamingResources>
            <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase" />
            </GlobalNamingResources>
            <Service name="Catalina">
            <Connector connectionTimeout="20000" port="{}" protocol="HTTP/1.1" redirectPort="8490" />
            <Engine defaultHost="localhost" name="Catalina">
                <Realm className="org.apache.catalina.realm.LockOutRealm">
                <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase" />
                </Realm>
                <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
                <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log" suffix=".txt" />
                </Host>
            </Engine>
            </Service>
        </Server>'''.format(port2,port)
        public.WriteFile(__server_config, ret)
        tomcat_bin = _setup_path+ '/' + name + version + '/bin'
        jdk_path = __path + '/jdk'
        jdks = []
        public.bt_print("正在获取JDK版本列表.")
        if os.path.exists(jdk_path):
            import re
            for filename in os.listdir(jdk_path): jdks.append(filename)
            n_jdks = []
            for jdkv in jdks: 
                try:
                    rRet = public.ExecShell('%s/jdk/%s/bin/java.exe -version' % (__path,jdkv))      
                    val = re.search('version\s+"(.+)"',rRet[1]).groups()[0]
                    n_jdks.append(jdkv)
                except : pass

            jdk_version = None
            jdk_list = __jdk_data[name + version]
            for x in n_jdks:
                if x in jdk_list:
                    jdk_version = x
                    break;     

            if not jdk_version:
                public.bt_print("缺少依赖JDK版本.")
                return False;

            public.bt_print("指定JDK版本为" + jdk_version)
            conf_list = ['catalina.bat','service.bat','startup.bat','shutdown.bat']
            for filename in conf_list:
               #print("11111111")
                conf = public.readFile(tomcat_bin + '/' + filename).replace("[PATH]",public.to_path(jdk_path + '/' + jdk_version))
                # if filename=='service.bat':
                #     print(conf)
                public.writeFile(tomcat_bin + '/' + filename,conf)
        #复制一个bak
        CopyDir(_setup_path+ '/' + name + version,_setup_path+ '/' + name + version+"_bak")

        public.bt_print("正在安装" + name + version + '服务...')
        os.system('%s && cd %s && service.bat install %s' % (_setup_path[0:2],tomcat_bin,"tomcatserver"+version))
        print('%s && cd %s && service.bat install %s' % (_setup_path[0:2],tomcat_bin,"tomcatserver"+version))
        public.change_server_start_type("tomcatserver" + version, 1)
        public.bt_print("正在启动" + name+"server" + version + '服务...')
        os.system("sc start " + name+"server" + version)

    public.bt_print("安装完成...")
    return True
    


if __name__ == "__main__":
    if len(sys.argv) > 2:        
        opt = sys.argv[1]
        name = sys.argv[2]
        version = sys.argv[3]
        if opt == 'uninstall':
            uninstall(name,version)
        else:
            install(name,version)
    else:
        public.bt_print("参数传递错误.")
