# ============================================
# BraceIQMed - Deploy to EC2 Server (Windows)
# Pushes to Gitea and updates server
# ============================================

param(
    [string]$Message = "Update deployment"
)

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  BraceIQMed - Deploy to Server" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# Configuration
$EC2_IP = "3.142.142.30"
$SSH_KEY = "C:\Users\msagh\OneDrive\Documents\GitHub\brace-final-key-2026.pem"
$REMOTE_DIR = "/home/ubuntu/DEPLOYMENTS/DEPLOYMENT_1"

# Change to project directory
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$projectDir = Split-Path -Parent $scriptDir
Set-Location $projectDir

Write-Host "[1/4] Checking for changes..." -ForegroundColor Yellow
$status = git status --porcelain
if ($status) {
    Write-Host "  Found uncommitted changes" -ForegroundColor Yellow
    
    Write-Host ""
    Write-Host "[2/4] Committing changes..." -ForegroundColor Yellow
    git add .
    git commit -m "$Message"
} else {
    Write-Host "  No local changes to commit" -ForegroundColor Green
}

Write-Host ""
Write-Host "[3/4] Pushing to Gitea..." -ForegroundColor Yellow
git push gitea main 2>&1
if ($LASTEXITCODE -ne 0) {
    Write-Host "  Note: Push to Gitea failed or not configured" -ForegroundColor Yellow
}

Write-Host ""
Write-Host "[4/4] Updating server..." -ForegroundColor Yellow

# SSH commands to update server
$sshCommands = @"
cd $REMOTE_DIR
echo 'Pulling latest changes...'
git pull origin main 2>/dev/null || echo 'Git pull skipped'
echo 'Rebuilding containers...'
docker compose build
echo 'Restarting containers...'
docker compose up -d
echo 'Checking status...'
sleep 5
docker compose ps
"@

ssh -i $SSH_KEY -o StrictHostKeyChecking=no ubuntu@$EC2_IP $sshCommands

Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "  Deployment complete!" -ForegroundColor Green
Write-Host "  Server: https://braceiqmed.com" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
