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


function Install {
    param (
        [string]$Version
    )

     #判断服务是否存在
    if (Get-Service -Name mysql -ErrorAction SilentlyContinue) {
        Invoke-Cmd -Command "sc stop mysql"
        Delete-Panel-Service -ServiceName "mysql"
    }

    #判断进程是否存在
    $mysqlProcess = Get-Process -Name "mysqld" -ErrorAction SilentlyContinue
    if ($mysqlProcess) {
        Stop-Process -Name "mysqld" -Force
    }
    
    # 区分vc++版本
    $VcVersion = "2015"
    if ($Version -eq "5.5") {
        $VcVersion =  "2008"
    } elseif ($Version -eq "5.6") {
        $VcVersion = "2010"
    } elseif ($Version -eq "5.7") {
        $VcVersion = "2012"
    } elseif ($Version -eq "8.0") {
        $VcVersion = "2015"
    }

    Lang-Print -Msg "正在安装{}:{}" -Arguments @("MySQL", $Version)
    if (-not (Setup-VCRedist -VcVersion $VcVersion)) {
        Lang-Print -Msg "运行库安装失败" -Arguments @("VC++ ")
        #return
    }

    # 定义 MySQL 安装路径
    $mysql_dir_path = "$SOFT_PATH/mysql"
    if (-not (Test-Path $mysql_dir_path)) {
        New-Item -Path $mysql_dir_path -ItemType Directory -Force
    }

    # 定义 MySQL 安装包路径
    $mysql_package_path =  "$SOFT_PATH/temp/MySQL.zip"
    $package_name = "MySQL$Version"   
    if ($Version -like "mariadb*") {
        $mariadbVersion = ($Version -match "\d+\.\d+") | Out-Null
        $package_name = "MariaDB-$($Matches[0])"
    }

    $DownUrl = "$DownNode/win/mysql/$package_name" + "_x64.zip"
    if (-not (Download-File -Url $DownUrl -OutputPath $mysql_package_path)) {
        Lang-Print -Msg "下载 {} 安装包失败" -Arguments @("MySQL")
        return
    }
    Lang-Print -Msg "正在解压 {} 安装包" -Arguments @("MySQL")
    Un-Zip -FilePath $mysql_package_path -DestinationPath $mysql_dir_path
    
    Lang-Print -Msg "解压{} 完成" -Arguments @("MySQL")

    $mysql_ini_file = "$mysql_dir_path/$package_name/my.ini"
    if (-not (Test-Path $mysql_ini_file)) {
        Lang-Print -Msg "{} 配置文件未找到: {}" -Arguments @("MySQL", $mysql_ini_file)
        return
    }

    $mysql_conf = Get-Content -Path $mysql_ini_file -Raw
    $mysql_dir = "$mysql_dir_path/$package_name"
    $mysql_dir = $mysql_dir -replace "\\", "/"

    #正则替换所有 [PATH] 为 MySQL 目录
    $mysql_conf = $mysql_conf -replace "\[PATH\]", $mysql_dir    
    Set-Content -Path $mysql_ini_file -Value $mysql_conf

    Remove-VersionFiles -Path $mysql_dir
    #安装 MySQL 服务
    $mysql_service_name = "mysql"
    $mysql_exe_path = "$mysql_dir_path/$package_name/bin/mysqld.exe"
    if (-not (Test-Path $mysql_exe_path)) {
        Lang-Print -Msg "{} 可执行文件未找到: {}" -Arguments @("MySQL", $mysql_exe_path)
        return
    }
    Lang-Print -Msg "正在安装{} 服务" -Arguments @($mysql_service_name)

    $BinaryPathName = "`"$mysql_exe_path`" --defaults-file=`"$mysql_ini_file`" MySQL"
    if (Install-Service -ServiceName $mysql_service_name -BinaryPathName $BinaryPathName -DisplayName "MySQL" -Description "MySQL Database Service") {
        Lang-Print -Msg "{} 服务安装成功" -Arguments @($mysql_service_name)
    } else {
        Lang-Print -Msg "{} 服务安装失败" -Arguments @($mysql_service_name)
        return
    }  
    #设置roo密码,随机16位        
    $bin_file = Get-PanelFile
    if (-not $bin_file) {
        Lang-Print -Msg "面板文件未找到" -Arguments @("")
        return
    }
    
    Lang-Print -Msg "正在设置 {} 密码" -Arguments @("MySQL root")
    $root_password = Generate-RandomString -Length 12
    Invoke-Cmd-WithOutput -Command "$bin_file --tools set_mysql_root $root_password"

    Lang-Print -Msg "正在同步 {} 数据库" -Arguments @("MySQL")
    Invoke-Cmd -Command "$bin_file --tools sync_to_database mysql"

    Lang-Print -Msg "MySQL 安装完成，root 密码为: {}" -Arguments @($root_password) 

    Lang-Print -Msg "正在启动 {} 服务已启动" -Arguments @($mysql_service_name)
    Invoke-Cmd -Command "sc start $mysql_service_name"

    Write-Host "Successfully"
    return
}

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

    Invoke-Cmd-NoOut -Command "taskkill /f /im mysqld.exe" 
    Invoke-Cmd-NoOut -Command "taskkill /f /im mysql.exe" 
    $mysql_service_name = "mysql"    
    if (Get-Service -Name $mysql_service_name -ErrorAction SilentlyContinue) {
        Invoke-Cmd -Command "sc stop $mysql_service_name"
        Delete-Panel-Service -ServiceName $mysql_service_name
    }
    Lang-Print -Msg "{} 卸载完成" -Arguments @("MySQL")
}

function Upgrade() {
    param (
        [string]$Version
    )
    Lang-Print -Msg "正在升级 {}" -Arguments @("MySQL")

    if (Get-Service -Name $mysql_service_name -ErrorAction SilentlyContinue) {
        Invoke-Cmd -Command "sc stop mysql"
    }
    
    $conf_file = "$SOFT_PATH/mysql/MySQL$Version/my.ini"
    Back-ConfigFile -FilePath $conf_file

    Install -Version $Version
    Restore-ConfigFile -FilePath $conf_file

    Lang-Print -Msg "{} 升级成功" -Arguments @("MySQL")
}

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