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


function Install {
    param (
        [string]$Version
    )

    $bit = "x86"
    if ([int]$Version -ge 55) {
        $bit = "x64"
    }

    Lang-Print -Msg "正在安装 PHP:{}" -Arguments @($Version)

    $VcVersion = switch -Regex ($Version) {
        "^(55|56)$"   { "2012"; break }
        "^(70|71)$"   { "2015"; break }
        "^(72|73|74)$" { "2017"; break }
        "^(80|81|82|83)$" { "2019"; break }  # 支持 PHP 8.x 和 9.x
        "^(8[4-9]|9\d)$"   { "2022"; break }  # 支持 PHP 8.x 和 9.x
        default        { "2015" }        # 默认值
    }

     if (-not (Setup-VCRedist -VcVersion $VcVersion)) {
        Write-Host "VC++ 运行库安装失败,请手动修复或者降低PHP版本"
        return
    }


    # 定义 PHP 安装包路径
    $php_package_path =  "$SOFT_PATH/temp/$Version.zip"
    $DownUrl = "$DownNode/win/php/$bit/$Version.zip"

    if (-not (Download-File -Url $DownUrl -OutputPath $php_package_path)) {
        Lang-Print -Msg "下载 PHP 安装包失败" -Arguments @("")
        return
    }
    Lang-Print -Msg "正在解压 {} 安装包" -Arguments @("PHP")
    # 定义 PHP 安装路径
    $php_dir_path = "$SOFT_PATH/php"
    
    Set-WebServer-Status -Status "stop"
    Un-Zip -FilePath $php_package_path -DestinationPath $php_dir_path

    if (-not (Test-Path $php_dir_path)) {
        Write-Host "PHP 安装失败"
        return
    }

    $lib_file = "$ROOT_PATH/data/phplib.win"
    $DownloadUrl = "$DownNode/win/panel/data/phplib.win"
    Download-File -Url $DownloadUrl -OutputPath $lib_file

    #添加权限
    Set-FileAccess -Path $php_dir_path -User "IIS_IUSRS" -Permission Modify -Recursive $true
    Set-FileAccess -Path "C:/Temp" -User "IIS_IUSRS" -Permission Full -Recursive $true
    Set-FileAccess -Path "C:/Windows/Temp" -User "IIS_IUSRS" -Permission Full -Recursive $true

    $php_ini_file = "$php_dir_path/$Version/php.ini"

    $soft_path = $SOFT_PATH -replace '/', '\\'
    $php_ini_body = Get-Content -Path $php_ini_file -Raw
    $php_ini_body = $php_ini_body -replace "\[PATH\]", $soft_path
    $php_ini_body = $php_ini_body -replace ';?upload_tmp_dir.+\n', 'upload_tmp_dir="C:/Temp"\n'
    Set-Content -Path $php_ini_file -Value $php_ini_body

    Remove-VersionFiles -Path $php_dir_path
    
    #安装 PHP FastCGI
    Set-Php
    $nginx_conf_file = "$SOFT_PATH/nginx/config.ini"
    if (Test-Path $nginx_conf_file) {
        
        $nginx_conf = Get-Content -Path $nginx_conf_file -Raw   
        $php_dirs = Get-ChildItem -Path $SOFT_PATH/php -Directory

        $php_versions = @()
        foreach ($dir in $php_dirs) {
            if ($dir.Name -match '^\d+(\.\d+)?$') {
                $php_versions += $dir.Name
            }
        }
        $nginx_conf = $nginx_conf -replace "php_versions\s?=.+", "php_versions = $($php_versions -join ',')"
        Set-Content -Path $nginx_conf_file -Value $nginx_conf

        Set-WebServer-Status -Status "restart"
    }
}

# iis追加PHP扩展
function Set-Php{
    
    #判断w3svc服务是否安装
    if (-not (Get-Service -Name w3svc -ErrorAction SilentlyContinue)) {      
        return
    }
    $Appcmd = Join-Path $env:windir "system32\inetsrv\appcmd.exe"
    
    # 定义循环次数
    for ($x = 0; $x -le 15; $x++) {
        Invoke-AppCmd-NoOut "set config /section:system.webServer/fastCGI /-[InstanceMaxRequests='10000']"
        Invoke-AppCmd-NoOut "set config /section:system.webServer/handlers /-[path='*.php']"
    }
    # 定义 PHP 安装路径
    $php_dir_path = Join-Path $SOFT_PATH "php"

    # 遍历 PHP 目录
    $phpDirs = Get-ChildItem -Path $php_dir_path -Directory
    foreach ($dir in $phpDirs) {
        $PhpCgiPath = Join-Path $dir.FullName "php-cgi.exe"
        $PhpIniPath = Join-Path $dir.FullName "php.ini"

        if (Test-Path $PhpCgiPath) {
            $phpVersion = $dir.Name
            Lang-Print -Msg "正在安装 PHP-{} 扩展" -Arguments @($phpVersion)

            Invoke-AppCmd "set config /section:system.webServer/fastCGI /+[fullPath='$PhpCgiPath']"
            Invoke-AppCmd-NoOut "set config /section:system.webServer/handlers /+[name='PHP_FastCGI',path='*.php',verb='*',modules='FastCgiModule',scriptProcessor='$PhpCgiPath',resourceType='File']"
            Invoke-AppCmd-NoOut "set config -section:system.webServer/defaultDocument /+`"files.[value='index.php']`" /commit:apphost"
            Invoke-AppCmd "set config -section:system.webServer/fastCGI /[fullPath='$PhpCgiPath'].instanceMaxRequests:10000"
            Invoke-AppCmd "set config -section:system.webServer/fastCgi /[fullPath='$PhpCgiPath',arguments=''].activityTimeout:`"90`" /commit:apphost"
            Invoke-AppCmd "set config -section:system.webServer/fastCgi /[fullPath='$PhpCgiPath',arguments=''].requestTimeout:`"90`" /commit:apphost"
            Invoke-AppCmd "set config -section:system.webServer/fastCgi /[fullPath='$PhpCgiPath'].monitorChangesTo:`"$PhpIniPath`""
            Invoke-AppCmd "set config -section:system.webServer/fastCgi /+`"[fullPath='$PhpCgiPath'].environmentVariables.[name='PHP_FCGI_MAX_REQUESTS',value='10000']`""
        }
    }
}

function Invoke-AppCmd {
    param([string]$Command)
    Start-Process -FilePath "cmd.exe" -ArgumentList "/c $Appcmd $Command" -Wait -NoNewWindow
}

function Invoke-AppCmd-NoOut {
    param([string]$Command)
  
    cmd /c "$Appcmd $Command" > $null 2>&1
}

function UnInstall {
    param (
        [string]$Version
    )
    
    Lang-Print -Msg "正在卸载 PHP:{}" -Arguments @($Version)
    $php_dir_path = "$SOFT_PATH/php/$Version"

    $process_list = @("httpd.exe", "nginx_server.exe","nginx.exe","w3wp.exe","php-cgi.exe")
    foreach ($process_name in $process_list) {
        $process = Get-Process -Name $process_name -ErrorAction SilentlyContinue
        if ($process) {
            Stop-Process -Name $process_name -Force
        }
    }

    Set-WebServer-Status -Status "stop"
    # 删除 PHP 目录
    if (Test-Path $php_dir_path) {
        Remove-Item -Path $php_dir_path -Recurse -Force -ErrorAction SilentlyContinue
    }
    Set-WebServer-Status -Status "start"
}


function Upgrade() {
    param (
        [string]$Version
    )

    Set-WebServer-Status -Status "stop"
    $conf_file = "$SOFT_PATH/php/$Version/php.ini"
    Back-ConfigFile -FilePath $conf_file

    Install -Version $Version

    Restore-ConfigFile -FilePath $conf_file
    Set-WebServer-Status -Status "start"
    Lang-Print -Msg "{} 升级成功" -Arguments @($Version)
}

$Version = $Version -replace '\.', ''

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