#!/bin/bash
set -e

APP_NAME="${1:-cv-server}"
SERVICE_NAME="${2:-cv}"
DEPLOY_PATH="${DEPLOY_PATH:-/home/txeo/Git/yo/cv}"

echo "🚀 Starting deployment of $APP_NAME"
echo "📍 Deploy path: $DEPLOY_PATH"
echo "🔧 Service: $SERVICE_NAME"

# Create backup of current version
if [ -f "$DEPLOY_PATH/$APP_NAME" ]; then
    echo "📦 Backing up current version..."
    BACKUP_DIR="$DEPLOY_PATH/backups"
    mkdir -p "$BACKUP_DIR"
    TIMESTAMP=$(date +%Y%m%d_%H%M%S)
    cp "$DEPLOY_PATH/$APP_NAME" "$BACKUP_DIR/$APP_NAME.$TIMESTAMP"

    # Keep only last 5 backups
    ls -t "$BACKUP_DIR" | tail -n +6 | xargs -I {} rm -f "$BACKUP_DIR/{}"
    echo "✓ Backup created: $APP_NAME.$TIMESTAMP"
fi

# Move new binary into place
echo "📥 Installing new version..."
mv "$DEPLOY_PATH/$APP_NAME.new" "$DEPLOY_PATH/$APP_NAME"
chmod +x "$DEPLOY_PATH/$APP_NAME"

# Restart service
echo "🔄 Restarting service..."
sudo systemctl restart "$SERVICE_NAME"

# Wait for service to start
sleep 3

# Check service status
if sudo systemctl is-active --quiet "$SERVICE_NAME"; then
    echo "✅ Service started successfully"

    # Get service status
    echo ""
    echo "📊 Service Status:"
    sudo systemctl status "$SERVICE_NAME" --no-pager -l | head -15

    echo ""
    echo "🎉 Deployment completed successfully"
    exit 0
else
    echo "❌ Service failed to start - rolling back"

    # Rollback to backup
    LATEST_BACKUP=$(ls -t "$BACKUP_DIR" 2>/dev/null | head -1)
    if [ -n "$LATEST_BACKUP" ]; then
        echo "⏪ Rolling back to: $LATEST_BACKUP"
        cp "$BACKUP_DIR/$LATEST_BACKUP" "$DEPLOY_PATH/$APP_NAME"
        sudo systemctl restart "$SERVICE_NAME"

        if sudo systemctl is-active --quiet "$SERVICE_NAME"; then
            echo "⚠️  Rolled back to previous version successfully"
        else
            echo "❌ Rollback failed - manual intervention required"
        fi
    else
        echo "❌ No backup found - manual intervention required"
    fi

    exit 1
fi
