#!/usr/bin/python
#coding: utf-8

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

class panel_sqlserver:
    _name = 'MSSQLSERVER'
    _version = None
    _setup_path = None

    def __init__(self,name,version,setup_path):
        self._version = version
        self._setup_path = setup_path

    def install_soft(self,downurl):
        if public.get_server_status(self._name) >= 0:  
            exit("已安装SQL Server服务，请勿重复安装！")

        public.bt_print('准备安装SQL.')
        path = self._setup_path + '/sqlserver'
        if not os.path.exists(path): os.makedirs(path)
       
        data = public.get_pip_list()
        if not 'pymssql' in data: 
            os.system(public.get_run_pip('[PIP] install pymssql'))
            data = public.get_pip_list()
            if not 'pymssql' in data: 
                os.system(public.get_run_pip('[PIP] install pymssql -i http://pypi.douban.com/simple'))
        
        public.bt_print('开始安装SQL%s.' % self._version)

        temp = path + '/' + self._version + '.rar'        
        public.bt_print('正在下载SQL%s.' % self._version)
        try:            
            public.downloadFileByWget(downurl + '/win/SqlServer/sql'+ self._version +'_x64.rar',temp)
        except :
            public.downloadFile(downurl + '/win/SqlServer/sql'+ self._version +'_x64.rar',temp)
        
        if not os.path.exists(temp): 
            return public.returnMsg(False,'文件下载失败,请检查网络!');

        public.bt_print('正在解压SQL.')
        from unrar import rarfile
        rar = rarfile.RarFile(temp)  
        rar.extractall(path)

        public.bt_print('正在配置SQL.')
        sa_pwd = public.GetRandomString(10).upper() + public.GetRandomString(10).lower() + str(time.time())[-3:]
        public.writeFile(panelPath+'/data/sa.pl',sa_pwd)

        public.writeFile(path + '/version.pl',self._version)
        if self._version == '2005':
            #手动安装
            cPath = path + '/setup.bat'
            config = public.readFile(cPath).replace('[PASSWORD]',sa_pwd).replace("[PATH]",path.replace('/','\\'))
            
            public.writeFile(cPath,config,'w+','gbk')

            error = 'Windows无法自动安装此程序，请手动运行安装目录【setup.bat】进行一键安装.'
            public.bt_print(error)
            return public.returnMsg(False,error)
        else:
            public.bt_print('正在启用.Net3.5（2-3分钟）')
            #2008不识别/all 2012以上需要/all安装前置依赖
            os.system("DISM /Online /Enable-Feature /FeatureName:NetFx3")
            os.system("DISM /Online /Enable-Feature /all /FeatureName:NetFx3")            
          
            cPath = path + '/ConfigurationFile.ini'
            if not os.path.exists(cPath):
                return public.returnMsg(False,'文件下载失败,请检查网络1!');

            #更新配置
            config = public.readFile(cPath).replace('[PATH]',path.replace('/','\\')).replace('[PASSWORD]',sa_pwd)
            public.writeFile(cPath,config)

            exe_path = '%s\SQLEXPR_%s_x64\setup.exe' % (path.replace('/','\\'),self._version)
            if self._version == '2008' or self._version == '2012':
                exe_path = '%s\SQLEXPR_%s_x64.exe' % (path.replace('/','\\'),self._version)
    
        public.bt_print('开始安装SQL%s.' % self._version)
        to_shell = "";
        if self._version == '2017':
            to_shell = "%s\\SSMS-Setup-CHS.exe" % (path.replace('/','\\'));
    
        tps = '@echo 安装完成，由于SQL Server需要GUI支持，如果需要通过面板管理您还需要做如下操作：\r\n@echo 1、通过管理工具连接上SQL Server\r\n@echo 2、依次找到安全性 - 登录名 - NT AUTHORITY\SYSTEM - 属性 - 服务器角色 -勾选列表中的sysadmin\r\n@echo 3、重启SQL Server服务\r\n@echo 4、完成安装'
        shell = 'cd %s \r\n%s \r\n%s /QS /ACTION=Install /ConfigurationFile=%s\ConfigurationFile.ini /IACCEPTSQLSERVERLICENSETERMS  /SAPWD="%s" /SQLSYSADMINACCOUNTS="Administrator" \r\n%s\r\n%s\r\n%s\r\npause' % (path.replace('/','\\'),'@echo 正在安装SQL，多次失败可尝试重启服务器后继续安装... ',exe_path,path.replace('/','\\'),sa_pwd,"@echo 安装成功",to_shell,tps)    

        public.writeFile(path + '/setup.bat',shell,'w+','gbk')
        public.bt_print(shell)
        result = public.ExecShell(shell)

        if public.get_server_status(self._name) >= 0:
            public.bt_print('安装完成.')
            return public.returnMsg(True,'安装成功!');

        error = 'Windows无法自动安装此程序，请手动运行安装目录【setup.bat】进行一键安装'
        public.bt_print(error)
        return public.returnMsg(False,error)

    def uninstall_soft(self):
        if public.get_server_status(self._name) >= 0:  public.delete_server(self._name)
        return public.returnMsg(True,'卸载成功!');

    def update_soft(self,downurl):
        pass
