#!/bin/bash
# ============================================
# BraceIQMed - Deploy to EC2 Server (Linux/Mac)
# Pushes to Gitea and updates server
# ============================================

set -e

# Configuration
EC2_IP="3.142.142.30"
SSH_KEY="$HOME/.ssh/brace-final-key-2026.pem"
REMOTE_DIR="/home/ubuntu/DEPLOYMENTS/DEPLOYMENT_1"

MESSAGE="${1:-Update deployment}"

echo "========================================"
echo "  BraceIQMed - Deploy to Server"
echo "========================================"
echo ""

# Change to project directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
cd "$PROJECT_DIR"

echo "[1/4] Checking for changes..."
if [[ -n $(git status --porcelain) ]]; then
    echo "  Found uncommitted changes"
    
    echo ""
    echo "[2/4] Committing changes..."
    git add .
    git commit -m "$MESSAGE"
else
    echo "  No local changes to commit"
fi

echo ""
echo "[3/4] Pushing to Gitea..."
git push gitea main 2>&1 || echo "  Note: Push to Gitea failed or not configured"

echo ""
echo "[4/4] Updating server..."

ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no ubuntu@$EC2_IP << 'EOF'
cd /home/ubuntu/DEPLOYMENTS/DEPLOYMENT_1
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
EOF

echo ""
echo "========================================"
echo "  Deployment complete!"
echo "  Server: https://braceiqmed.com"
echo "========================================"
