# 前端部署脚本 
# 日期：2025-08-07

# ===== 配置区域 =====
$sourceDir = "D:\project\ln-web\dist"
$remoteUser = "liujia"
$remoteIP = "43.137.10.199"
$remotePath = "/work/web/src"
$sshPort = 22
# ====================

# 创建时间戳压缩包
$timestamp = Get-Date -Format "yyyyMMddHHmmss"
$zipPath = "D:\project\dist-$timestamp.zip"

Write-Host "🗜️ 正在压缩文件..." -ForegroundColor Cyan
Compress-Archive -Path "$sourceDir\*" -DestinationPath $zipPath -CompressionLevel Optimal
$zipSizeMB = [math]::Round((Get-Item $zipPath).Length / 1MB, 2)

Write-Host "🚀 传输压缩包到服务器 ($zipSizeMB MB)..." -ForegroundColor Cyan
scp -P $sshPort $zipPath "${remoteUser}@${remoteIP}:~/dist-latest.zip"

Write-Host "📦 服务器端解压..." -ForegroundColor Cyan

# 执行压缩包解压命令
$sshCommand = "mkdir -p '$remotePath' && unzip -qo ~/dist-latest.zip -d '$remotePath' && rm ~/dist-latest.zip"

# 执行命令并捕获输出
$result = ssh -p $sshPort ${remoteUser}@${remoteIP} $sshCommand 2>&1

# 检查命令执行状态
if ($LASTEXITCODE -eq 0) {
    $success = $true
    Write-Host "✅ 服务器解压成功" -ForegroundColor Green
} else {
    $success = $false
    Write-Host "❌ 服务器解压失败: $result" -ForegroundColor Red
}

Write-Host "🧹 清理本地文件..." -ForegroundColor DarkGray
Remove-Item $zipPath -ErrorAction SilentlyContinue

if ($success) {
    Write-Host "✅ 部署完成! 压缩包大小: $zipSizeMB MB" -ForegroundColor Green
} else {
    Write-Host "❌ 部署失败!" -ForegroundColor Red
    Write-Host "手动修复命令:" -ForegroundColor Yellow
    Write-Host "ssh -p $sshPort ${remoteUser}@${remoteIP} 'unzip -o ~/dist-latest.zip -d `"$remotePath`"'"
    
    # 添加额外诊断信息
    Write-Host "`n诊断信息:" -ForegroundColor Cyan
    Write-Host "1. 确保目标目录存在:"
    Write-Host "   ssh -p $sshPort ${remoteUser}@${remoteIP} 'ls -ld `"$remotePath`"'"
    
    Write-Host "2. 检查磁盘空间:"
    Write-Host "   ssh -p $sshPort ${remoteUser}@${remoteIP} 'df -h'"
    
    Write-Host "3. 检查文件权限:"
    Write-Host "   ssh -p $sshPort ${remoteUser}@${remoteIP} 'stat `"$remotePath`"'"
}