#!/bin/bash
set -e

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

echo "⏪ Rollback Script for $APP_NAME"
echo "📍 Deploy path: $DEPLOY_PATH"
echo "🔧 Service: $SERVICE_NAME"
echo ""

# Check if backup directory exists
if [ ! -d "$BACKUP_DIR" ]; then
    echo "❌ No backup directory found at $BACKUP_DIR"
    exit 1
fi

# List available versions
echo "📦 Available backup versions:"
ls -lht "$BACKUP_DIR" | tail -n +2 | head -5 | awk '{print NR". "$9" ("$6" "$7" "$8")"}'
echo ""

# If no argument provided, show usage
if [ -z "$3" ]; then
    echo "Usage: $0 <app_name> <service_name> <version_number>"
    echo "Example: $0 cv-server cv 1"
    echo ""
    echo "Or to rollback to the most recent version:"
    echo "  $0 cv-server cv latest"
    exit 0
fi

VERSION_ARG="$3"

# Determine which backup to use
if [ "$VERSION_ARG" = "latest" ]; then
    BACKUP_FILE=$(ls -t "$BACKUP_DIR" | head -1)
    echo "🔍 Selected: latest version ($BACKUP_FILE)"
else
    BACKUP_FILE=$(ls -t "$BACKUP_DIR" | sed -n "${VERSION_ARG}p")
    echo "🔍 Selected: version #$VERSION_ARG ($BACKUP_FILE)"
fi

if [ -z "$BACKUP_FILE" ]; then
    echo "❌ Version not found"
    exit 1
fi

# Confirm rollback
echo ""
echo "⚠️  About to rollback to: $BACKUP_FILE"
read -p "Continue? (yes/no): " CONFIRM

if [ "$CONFIRM" != "yes" ]; then
    echo "❌ Rollback cancelled"
    exit 0
fi

# Create backup of current version before rollback
if [ -f "$DEPLOY_PATH/$APP_NAME" ]; then
    TIMESTAMP=$(date +%Y%m%d_%H%M%S)
    cp "$DEPLOY_PATH/$APP_NAME" "$BACKUP_DIR/$APP_NAME.pre-rollback.$TIMESTAMP"
    echo "✓ Current version backed up as: $APP_NAME.pre-rollback.$TIMESTAMP"
fi

# Perform rollback
echo "⏪ Rolling back..."
cp "$BACKUP_DIR/$BACKUP_FILE" "$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 "✅ Rollback successful - service is running"
    echo ""
    echo "📊 Service Status:"
    sudo systemctl status "$SERVICE_NAME" --no-pager -l | head -15
    exit 0
else
    echo "❌ Service failed to start after rollback"
    echo ""
    echo "🔍 Service logs:"
    sudo journalctl -u "$SERVICE_NAME" -n 20 --no-pager
    exit 1
fi
