$OutputEncoding = [System.Text.Encoding]::UTF8
function deploy {
    param(
        [string]$username_param,
        [string]$ip_address_param,
        [string]$folder_name_param,
        [string]$server_path_param,
        [string]$zip_filename_param
    )

    # 判断7z命令是否可用
    $7zPath = Get-Command 7z -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source
    if (-not $7zPath) {
        Write-Host "7z command is not available! Please run 'npm install -g 7zip' first."
        return
    }
    
    Write-Host "7z command is available at: $7zPath"

    # 压缩打包后的文件，可用`npm install -g 7zip`全局安装7z命令
    7z a $zip_filename_param ./dist/*

    [System.Console]::InputEncoding = [System.Text.Encoding]::GetEncoding("GB18030")
    if ($LASTEXITCODE -eq 0) {
        Write-Host "Compressing files successful"
        # Write-Host "压缩打包成功"
    }
    else {
        Write-Host "Compressing files failed"
        # Write-Host "压缩打包失败"
        return 1
    }

    # 迁移压缩文件到服务器对应目录下
    $scpCommand = "scp ./${zip_filename_param} ${username_param}@${ip_address_param}:${server_path_param}"
    Invoke-CommandWithDebug -Command $scpCommand
    # Invoke-Expression $scpCommand

    if ($LASTEXITCODE -eq 0) {
        Write-Host "File transfer successful"
        # Write-Host "文件迁移成功"
    }
    else {
        Write-Host "File transfer failed"
        # Write-Host "文件迁移失败"
        return 1
    }

    # 删除上传后的压缩文件
    Remove-Item $zip_filename_param -Force

    # 在服务器上解压缩文件
    $sshCommand = "ssh $username_param@$ip_address_param `"cd $server_path_param && unzip -o $zip_filename_param -d $folder_name_param && chmod -R 775 $folder_name_param && rm $zip_filename_param`""
    Invoke-CommandWithDebug -Command $sshCommand
    # Invoke-Expression $sshCommand

    if ($LASTEXITCODE -eq 0) {
        Write-Host "Unzipping successful"
        # Write-Host "解压缩成功"
    }
    else {
        Write-Host "Unzipping failed"
        # Write-Host "解压缩失败"
        return 1
    }

    Write-Host "Congratulations: $folder_name_param deployment successful! "
    # Write-Host "恭喜：$folder_name_param 发布圆满成功!🎉🚀"
    return 0
}

function Invoke-CommandWithDebug {
    param (
        [string]$Command
    )

    Write-Host "Executing command: $Command"
    Invoke-Expression $Command
}

# 调用deploy函数，并传递配置项参数
$username_param = "clear"
$ip_address_param = "192.168.30.153" # 测试环境
$folder_name_param = "selfMarketing"
$server_path_param = "/home/clear/frontend/"
$zip_filename_param = "build.zip"

deploy -username_param $username_param -ip_address_param $ip_address_param -folder_name_param $folder_name_param -server_path_param $server_path_param -zip_filename_param $zip_filename_param

#############################################
# 中文乱码，暂时换成英文提示    
# npm run publish:dev
# deploy_dev.sh需要git-bash，在Win下不太方便，
# 故增加本等效的powershell部署脚本。
#############################################