# UTF-8 Encoding Setup
[Console]::OutputEncoding = [Text.UTF8Encoding]::new()
chcp 65001 > $null

# ===== Settings =====
$KEY = ".\1.key"
$USER = "ubuntu"
$REMOTE_HOST = "129.154.58.6"
$REMOTE_DIR = "/var/www/bandosj.com/public_html"
$ARCHIVE_NAME = "dist.tar.gz"

# ===== Compress =====
Write-Host "📦 Compressing dist directory..."
tar -czf $ARCHIVE_NAME -C dist .

# ===== Transfer file =====
Write-Host "🚀 Uploading archive file..."
# Use braces to avoid variable parsing errors in PowerShell
scp -i $KEY $ARCHIVE_NAME "${USER}@${REMOTE_HOST}:/tmp/${ARCHIVE_NAME}"
if ($LASTEXITCODE -ne 0) {
    Write-Error "❌ File transfer failed"
    exit 1
}

# ===== Extract and deploy on remote server =====
Write-Host "🔧 Deploying on remote server..."
ssh -i $KEY "$USER@$REMOTE_HOST" @"
    sudo mkdir -p '$REMOTE_DIR'
    sudo rm -rf '$REMOTE_DIR/*'
    sudo tar -xzf /tmp/$ARCHIVE_NAME -C '$REMOTE_DIR'
    sudo rm /tmp/$ARCHIVE_NAME
"@

# ===== Clean up local =====
Remove-Item $ARCHIVE_NAME

# ===== Done =====
Write-Host "✅ Deployment complete! Check your site at http://bandosj.com"
