#!/usr/bin/python
#coding: utf-8
#-----------------------------
# 安装脚本
#-----------------------------
import public,os,time,re
class panel_iis:
    _name = None
    _version = None
    _setup_path = None
    _iis_root = None
    _app_cmd = None
    _local_path = None

    def __init__(self,name,version,setup_path):
        self._name = name
        self._version = version
        self._setup_path = setup_path
        self._iis_root = os.getenv("SYSTEMDRIVE") + '\\Windows\\System32\\inetsrv'
        self._app_cmd = self._iis_root + '\\appcmd.exe'
        self._local_path = self._setup_path + '/temp'

    def install_soft(self,downurl):
        public.bt_print('正在安装IIS,需要5-10分钟...')
        public.bt_print('如果此进度超过10分钟，您可能需要进入服务器手动安装IIS（手动安装后需要通过面板再安装一次）或者重启下服务器后重新安装...')
        os.system("start /w pkgmgr /iu:IIS-WebServerRole;IIS-WebServer;IIS-CommonHttpFeatures;IIS-StaticContent;IIS-DefaultDocument;IIS-DirectoryBrowsing;IIS-HttpErrors;IIS-HttpRedirect;IIS-ApplicationDevelopment;IIS-ASP;IIS-CGI;IIS-ISAPIExtensions;IIS-ISAPIFilter;IIS-ServerSideIncludes;IIS-HealthAndDiagnostics;IIS-HttpLogging;IIS-LoggingLibraries;IIS-RequestMonitor;IIS-HttpTracing;IIS-CustomLogging;IIS-ODBCLogging;IIS-Security;IIS-BasicAuthentication;IIS-WindowsAuthentication;IIS-DigestAuthentication;IIS-ClientCertificateMappingAuthentication;IIS-IISCertificateMappingAuthentication;IIS-URLAuthorization;IIS-RequestFiltering;IIS-IPSecurity;IIS-Performance;IIS-HttpCompressionStatic;IIS-HttpCompressionDynamic;IIS-WebServerManagementTools;IIS-ManagementScriptingTools;IIS-ASPNET;IIS-NetFxExtensibility;IIS-ManagementService;IIS-ManagementConsole;IIS-IIS6ManagementCompatibility; /norestart")

        status = public.get_server_status('W3SVC')
        if status == -1:
            public.bt_print('IIS安装失败，您可能需要重启下服务器...')
            time.sleep(2)
            return public.returnMsg(False,'IIS安装失败...')

        public.bt_print('正在设置iis日志目录...')
        logPath = (self._setup_path + '/wwwlogs').replace('/','\\')
        if not os.path.exists(logPath):
            os.makedirs(logPath)
        public.ExecShell(self._app_cmd + ' set config -section:system.applicationHost/sites /siteDefaults.logFile.directory:"' + logPath + '" /commit:apphost')

        public.bt_print('正在启用asp...')
        public.ExecShell(self._app_cmd + ' set config /section:asp /enableParentPaths:True')
        public.ExecShell(self._app_cmd + ' set config /section:anonymousAuthentication /userName:\"\"')

        public.bt_print('正在启用.Net3.5（2-3分钟）')
        #2008不识别/all 2012以上需要/all安装前置依赖
        os.system("DISM /Online /Enable-Feature /FeatureName:NetFx3 /n")
        os.system("DISM /Online /Enable-Feature /all /FeatureName:NetFx3 /n")
        #2016需要安装4.5
        os.system("DISM /online /enable-feature /all /featurename:IIS-ASPNET45 /n")

        public.bt_print('正在优化iis默认页...')
        default_list = ['default.html','default.asp','default.aspx','index.php','index.asp','index.aspx']
        for key in default_list:  public.ExecShell(self._app_cmd + " set config /section:defaultDocument /+files.[value='" + key + "']")

        try:
            iis_reg = 'SOFTWARE\Microsoft\InetStp'
            iisVersion = public.ReadReg(iis_reg,'MajorVersion')
            if iisVersion > 9:  public.WriteReg(iis_reg,'MajorVersion',9)
        except :
            pass

        if not public.isAppSetup("IIS URL"):
            public.bt_print('正在下载URLRewrite文件...')
            public.downloadFile(downurl + '/win/URLRewrite_x64.msi',self._local_path + '/URLRewrite.msi')
            if not os.path.exists(self._local_path + '/URLRewrite.msi'): return public.returnMsg(False,'URL重写扩展下载失败,请检查网络是否正常..')

            public.bt_print("正在启动iis...")
            public.ExecShell("iisreset /START")
            time.sleep(1)

            public.bt_print("正在安装URLRewrite...")
            public.ExecShell(self._local_path + '/URLRewrite.msi /qb')
            time.sleep(1)

        public.writeFile(os.getenv('BT_PANEL') + '/data/iis.setup',"True")
        pPath = self._setup_path + '/php'
        if os.path.exists(pPath):
            public.bt_print("正在设置PHP扩展...")
            try:
                for x in [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]:
                    public.ExecShell(self._app_cmd + " set config /section:system.webServer/fastCGI /-[InstanceMaxRequests='10000']")
                    public.ExecShell(self._app_cmd + " set config /section:system.webServer/handlers /-[path='*.php']")
            except :
                pass
            for filename in os.listdir(pPath):
                cgiPath = (pPath + '/'+ filename + "/php-cgi.exe").replace('/','\\')
                iniPath = (pPath + '/'+ filename + "/php.ini").replace('/','\\')
                if os.path.exists(cgiPath):
                    public.bt_print("正在安装PHP-" + filename + "扩展...")
                    public.ExecShell(self._app_cmd + " set config /section:system.webServer/fastCGI /+[fullPath='" + cgiPath + "']")
                    public.ExecShell(self._app_cmd + " set config /section:system.webServer/handlers /+[name='PHP_FastCGI',path='*.php',verb='*',modules='FastCgiModule',scriptProcessor='" + cgiPath + "',resourceType='File']")

                    public.ExecShell(self._app_cmd + " set config -section:system.webServer/defaultDocument /+\"files.[value='index.php']\" /commit:apphost")
                    public.ExecShell(self._app_cmd + " set config -section:system.webServer/fastCGI /[fullPath='" + cgiPath + "'].instanceMaxRequests:10000")
                    public.ExecShell(self._app_cmd + " set config -section:system.webServer/fastCgi /[fullPath='" + cgiPath + "',arguments=''].activityTimeout:\"90\"  /commit:apphost")
                    public.ExecShell(self._app_cmd + " set config -section:system.webServer/fastCgi /[fullPath=''" + cgiPath + "',arguments=''].requestTimeout:\"90\"  /commit:apphost")
                    public.ExecShell(self._app_cmd + " set config -section:system.webServer/fastCgi /[fullPath='" + cgiPath + "'].monitorChangesTo:\"" + iniPath   + "\"")
                    public.ExecShell(self._app_cmd + " set config -section:system.webServer/fastCgi /+\"[fullPath='" + cgiPath + "'].environmentVariables.[name='PHP_FCGI_MAX_REQUESTS',value='10000']\"")

        public.bt_print("正在设置回环地址...")
        host_path = "C:\Windows\System32\drivers\etc\hosts"
        if os.path.exists(host_path):
            hosttxt = public.readFile(host_path)
            tmp = re.search('\n\s*127.0.0.1\s+localhost',hosttxt)
            if not tmp:
                public.writeFile(host_path,hosttxt +  '\n127.0.0.1 localhost')

        public.bt_print("正在配置IIS...")
        public.ExecShell(self._app_cmd + " unlock config -section:system.webServer/handlers")
        public.ExecShell("regsvr32 /u /s %windir%\system32\wshom.ocx")
        public.ExecShell("regsvr32 /u /s %windir%\system32\shell32.dll")

        public.bt_print("正在优化IIS...")
        public.ExecShell(self._app_cmd + ' set config /section:system.webServer/serverRuntime /appConcurrentRequestLimit:100000')
        public.ExecShell("reg add HKLM\System\CurrentControlSet\Services\HTTP\Parameters /v MaxConnections /t REG_DWORD /d 100000 /f");

        public.ExecShell("reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\HTTP\Parameters /v MaxFieldLength /t REG_DWORD /d 32768 /f");
        public.ExecShell("reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\HTTP\Parameters /v MaxRequestBytes /t REG_DWORD /d 32768 /f");

        public.bt_print("正在启动IIS...")
        public.change_server_start_type('W3SVC',1)
        public.WriteReg(r'SYSTEM\CurrentControlSet\services\HTTP','Start',3)

        os.system('iisreset /start')
        public.M('config').where("id=?",('1',)).setField('webserver','iis')
        public.bt_print("正在安装ASP.NET...")

        os.system('dism /online /enable-feature /featurename:IIS-ASPNET45');
        os.system('dism /online /enable-feature /all /featurename:IIS-ASPNET45');
        os.system(self._app_cmd + " set config /section:staticContent /+[fileExtension='.',mimeType='text/plain']")



        public.bt_print("iis安装完成")

        self.create_default_site()

        return public.returnMsg(True,'iis安装完成')

    def get_ip_address(self):

        """
        取本地外网IP
        """
        try:

            url = 'http://pv.sohu.com/cityjson?ie=utf-8'
            str = public.httpGet(url)
            ipaddress = re.search('\d+.\d+.\d+.\d+', str).group(0)

            return ipaddress
        except:
            try:
                url = 'https://www.bt.cn/Api/getIpAddress'
                str = public.httpGet(url)
                return str
            except:
                False

    def create_default_site(self):
        """
        @name 创建默认站点
        """

        t_path = '{}/data/default.site'.format(public.get_panel_path())
        if not os.path.exists(t_path):
            try:

                print('正在创建默认站点...')
                siteName = self.get_ip_address()
                if not siteName: return

                find = public.M('config').where("id=?",('1',)).find()
                if not find: return

                import panelSite,json
                site_obj = panelSite.panelSite()

                args = public.dict_obj()
                args.webname = json.dumps({"domain":siteName,"domainlist":[],"count":0})
                args.ps = '默认网站，将网站源码放入网站根目录即可访问'

                args.path = '{}/{}'.format(find['sites_path'],siteName)
                args.version = '00'
                args.port = '80'
                args.ftp = 'false'
                args.sql = 'false'

                res = site_obj.AddSite(args)
                if res['siteStatus']:
                    print('默认站点创建成功，访问地址: http://{}'.format(siteName))
                public.writeFile(t_path,'True')
            except:pass

    def uninstall_soft(self):
        public.bt_print("正在卸载iis...")
        if public.set_server_status("W3SVC","stop"):
            if public.change_server_start_type('W3SVC',-1):
                os.remove(os.getenv('BT_PANEL') + '/data/iis.setup')

                #删除phpmyadmin
                public.bt_print("卸载phpmyadmin.")
                self.del_phpmyadmin()

                public.bt_print("卸载成功.!")
                return public.returnMsg(True,'iis卸载成功.')
        public.bt_print("卸载失败.")
        return public.returnMsg(False,'iis卸载失败.')

       #删除网站
    def del_phpmyadmin(self):
        import shutil
        public.ExecShell(self._app_cmd + ' delete site "phpmyadmin"')
        public.ExecShell(self._app_cmd + ' delete apppool "phpmyadmin"')

        if os.path.exists(self._setup_path + '/phpmyadmin'):
            shutil.rmtree(self._setup_path + '/phpmyadmin')

    def update_soft(self):
        pass
