# 主脚本参数
param (
    [string]$Action, 
    [string]$Version
)
. .\comm.ps1 


function Install {
    param (
        [string]$Version
    )

    #判断服务是否存在
    if (Get-Service -Name MSSQLSERVER -ErrorAction SilentlyContinue) {
        Lang-Print -Msg "{} 服务已存在，请勿重复安装" -Arguments @("SQL Server")
        return 
    }

    Lang-Print -Msg "正在安装 {}: {}" -Arguments @("SQL Server", $Version)
    # 定义 SQL Server 安装路径
    $sql_dir_path = "$SOFT_PATH/sqlserver"
    if (-not (Test-Path $sql_dir_path)) {
        New-Item -Path $sql_dir_path -ItemType Directory -Force
    }
    # 定义 SQL Server 安装包路径
    $sql_package_path = "$SOFT_PATH/temp/sqlserver.zip"
    $DownUrl = "$DownNode/win/SqlServer/sql$Version" + "_x64.zip"
    if (-not (Download-File -Url $DownUrl -OutputPath $sql_package_path)) {
        Lang-Print -Msg "下载 {} 安装包失败" -Arguments @("SQL Server")
        return
    }
    Lang-Print -Msg "正在解压 {} 安装包" -Arguments @("SQL Server")
    Un-Zip -FilePath $sql_package_path -DestinationPath $sql_dir_path

    #随机8位密码
    $password = [System.Web.Security.Membership]::GeneratePassword(8, 4)
    $password = "sqlserver_$password"

    $sa_file = "$ROOT_PATH/data/sa.pl"
    if (-not (Test-Path -Path $sa_file)) {
        New-Item -Path $sa_file -ItemType File -Force | Out-Null
    }   
    Set-Content -Path $sa_file -Value $password
    Remove-VersionFiles -Path $sql_dir_path

    if ($Version -eq "2005") {
        
        $bat_file = "$sql_dir_path/setup.bat"
        if (-not (Test-Path -Path $bat_file)) {
            Lang-Print -Msg "SQL Server 2005 安装脚本未找到: {}" -Arguments @($bat_file)
            return
        }

        $sql_path = $sql_dir_path -replace "/", "\\"

        $conf = Get-Content -Path $bat_file -Raw
        $conf = $conf -replace "\[PASSWORD\]", $password
        $conf = $conf -replace "\[PATH\]", $sql_path

        Set-Content -Path $bat_file -Value $conf
        Lang-Print -Msg "Windows无法自动安装此程序，请手动运行安装目录【setup.bat】进行一键安装." -Arguments @("")
        return
    } else {
        Lang-Print -Msg "正在启用.Net3.5(2-3分钟)" -Arguments @("")
        Invoke-Cmd-NoOut "DISM /Online /Enable-Feature /FeatureName:NetFx3 /n"
        Invoke-Cmd-NoOut "DISM /Online /Enable-Feature /all /FeatureName:NetFx3 /n"
        Invoke-Cmd-NoOut "DISM /online /enable-feature /all /featurename:IIS-ASPNET45 /n"

        $ini_file = "$sql_dir_path/ConfigurationFile.ini"
        if (-not (Test-Path $ini_file)) {
            Lang-Print -Msg "SQL Server 配置文件未找到: {}" -Arguments @($ini_file)
            return
        }
        $conf = Get-Content -Path $ini_file -Raw
        $conf = $conf -replace "\[PASSWORD\]", $password
        $conf = $conf -replace "\[PATH\]", $sql_dir_path -replace "/", "\\"
        Set-Content -Path $ini_file -Value $conf

       # 根据版本动态设置安装文件路径
        $setup_file = "$sql_dir_path/SQLEXPR_${Version}_x64.exe"
        if ($Version -ne "2012" -and $Version -ne "2008") {
            $setup_file = "$sql_dir_path/SQLEXPR_${Version}_x64/setup.exe"
        }
        if (-not (Test-Path $setup_file)) {
            Lang-Print -Msg "{} 安装程序未找到: {}" -Arguments @("SQL Server", $setup_file)
            return
        }
       
        # 定义安装路径和配置文件路径
        $to_shell = ""
        if ($Version -eq "2017") {
            $to_shell = "$sql_dir_path/SSMS-Setup-CHS.exe"
        }

        $tip1 = Lang-Ctx -Msg "安装完成，由于 {} 需要 GUI 支持，如果需要通过面板管理您还需要做如下操作" -Arguments @("SQL Server")
        $tip2 = Lang-Ctx -Msg "通过管理工具连接上 {}" -Arguments @("SQL Server")
        $tip3 = Lang-Ctx -Msg "依次找到安全性 - 登录名 - NT AUTHORITY\SYSTEM - 属性 - 服务器角色 - 勾选列表中的 sysadmin" -Arguments @("")
        $tip4 = Lang-Ctx -Msg "重启 {} 服务" -Arguments @("SQL Server")
        $tip5 = Lang-Ctx -Msg "完成安装" -Arguments @("")

        # 定义安装完成后的提示信息
        $tps = "@echo $tip1 ：
        @echo $tip2
        @echo $tip3
        @echo $tip4
        @echo $tip5"

        $tip6 = Lang-Ctx -Msg "正在安装 {} 多次失败可尝试重启服务器后继续安装" -Arguments @("SQL Server")
        $tip7 = Lang-Ctx -Msg "安装成功" -Arguments @("")

# 构建安装脚本内容
$shell = @"
cd $sql_dir_path
@echo ...
`"$setup_file`" /QS /ACTION=Install /ConfigurationFile=`"$ini_file`" /IACCEPTSQLSERVERLICENSETERMS /SAPWD=`"$password`" /SQLSYSADMINACCOUNTS=`"Administrator`"
@echo $tip7
$to_shell
$tps
pause
"@

        # 写入安装脚本到 setup.bat 文件
        $bat_file = "$sql_dir_path/setup.bat"
        Set-Content -Path $bat_file -Value $shell -Encoding Default

        # 输出安装脚本路径
        Lang-Print -Msg "安装脚本已生成: {}" -Arguments @($bat_file)

        # 执行安装脚本
        Lang-Print -Msg "正在执行安装脚本..." -Arguments @("")
        Start-Process -FilePath "cmd.exe" -ArgumentList "/c `"$bat_file`"" -Wait -NoNewWindow

        Lang-Print -Msg "Windows无法自动安装此程序，请手动运行安装目录【setup.bat】进行一键安装." -Arguments @("")
        return
    }
}

function UnInstall {
    Lang-Print -Msg "正在卸载 {} 服务" -Arguments @("SQL Server")

    # 停止 SQL Server 服务
    if (Get-Service -Name MSSQLSERVER -ErrorAction SilentlyContinue) {
        Invoke-Cmd -Command "sc stop MSSQLSERVER"
        Invoke-Cmd -Command "sc delete MSSQLSERVER"
    }

    Lang-Print -Msg "{} 卸载完成" -Arguments @("SQL Server")
}


switch ($Action.ToLower()) {
    "install" {       
        Install -Version $Version
    }
    "uninstall" {
        UnInstall
    }    
}
