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


function Install {
    param (
        [string]$Version
    )
    Lang-Print -Msg "正在安装 {}:{}" -Arguments @("Apache",$Version)

    Invoke-Cmd -Command "net stop http /y"    
    Set-Service -Name W3SVC -StartupType Disabled

    # 判断服务是否存在
    if (Get-Service -Name apache -ErrorAction SilentlyContinue) {
        Lang-Print -Msg "{} 服务已存在，准备卸载" -Arguments @("Apache")
        Set-WebServer-Status -Status "stop"
        Delete-Panel-Service -ServiceName "apache"
    }
    # 定义 Apache 安装路径
    $apache_dir_path = "$SOFT_PATH/apache"
    if (-not (Test-Path $apache_dir_path)) {
        New-Item -Path $apache_dir_path -ItemType Directory -Force
    }

    $DownUrl = "$DownNode/win/apache_new/apache$Version.zip"
    $apache_package_path = "$SOFT_PATH/temp/apache.zip"

    if (-not (Download-File -Url $DownUrl -OutputPath $apache_package_path)) {
        Lang-Print -Msg "下载 {} 安装包失败" -Arguments @("Apache")
        return
    }
    Lang-Print -Msg "正在解压 {} 安装包" -Arguments @("Apache")
    Un-Zip -FilePath $apache_package_path -DestinationPath $SOFT_PATH

    $conf_file = "$apache_dir_path/conf/httpd.conf"
    if (Test-Path $conf_file) {
        $conf_body = Get-Content -Path $conf_file -Raw
        $conf_body = $conf_body -replace "\[PATH\]", $apache_dir_path
        Set-Content -Path $conf_file -Value $conf_body
    }

    Remove-VersionFiles -Path $apache_dir_path
    Invoke-Cmd -Command "$apache_dir_path/bin/httpd.exe -k install -n apache "
    Start-Service -Name apache

    Lang-Print -Msg "{} 服务安装成功" -Arguments @("Apache")
    Write-Host "Successfully"
}

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

    Set-WebServer-Status -Status "stop"

    $conf_file = "$SOFT_PATH/apache/conf/httpd.conf"
    Back-ConfigFile -FilePath $conf_file
    
    Install -Version $Version
    Restore-ConfigFile -FilePath $conf_file

    Start-Service -Name apache
    Lang-Print -Msg "{} 升级成功" -Arguments @("Apache")
}

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

    Set-WebServer-Status -Status "stop"
    Stop-Service -Name apache -Force    
    Delete-Panel-Service -ServiceName "apache"

    Lang-Print -Msg "{} 服务卸载成功" -Arguments @("Apache")
}


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