#!/bin/bash
# rollback.sh
# Emergency rollback script for MotoVaultPro
#
# Usage:
#   ./scripts/rollback.sh              # Rollback to previous commit (HEAD~1)
#   ./scripts/rollback.sh HEAD~2       # Rollback 2 commits back
#   ./scripts/rollback.sh v1.0.0       # Rollback to specific tag
#   ./scripts/rollback.sh abc123       # Rollback to specific commit
#
# This script:
#   1. Stops all running services
#   2. Checks out the specified version
#   3. Rebuilds Docker images
#   4. Starts all services
#   5. Runs basic health checks

set -euo pipefail

# Configuration
DEPLOY_PATH="${DEPLOY_PATH:-/opt/motovaultpro}"
ROLLBACK_TARGET="${1:-HEAD~1}"
DOCKER_COMPOSE_FILE="docker-compose.yml"
DOCKER_COMPOSE_PROD_FILE="docker-compose.prod.yml"

echo "=========================================="
echo "MotoVaultPro Rollback"
echo "=========================================="
echo "Deploy path: $DEPLOY_PATH"
echo "Target: $ROLLBACK_TARGET"
echo ""

cd "$DEPLOY_PATH"

# Confirm rollback
echo "WARNING: This will stop all services and rollback to: $ROLLBACK_TARGET"
echo ""
read -p "Continue? (y/N): " confirm
if [ "${confirm,,}" != "y" ]; then
    echo "Rollback cancelled"
    exit 0
fi

echo ""
echo "Step 1/5: Stopping current services..."
docker compose -f $DOCKER_COMPOSE_FILE -f $DOCKER_COMPOSE_PROD_FILE down --timeout 30 || true

echo ""
echo "Step 2/5: Recording current version for reference..."
CURRENT_COMMIT=$(git rev-parse HEAD)
echo "Current commit: $CURRENT_COMMIT"
echo "$CURRENT_COMMIT" > .rollback-from

echo ""
echo "Step 3/5: Checking out $ROLLBACK_TARGET..."
git fetch origin
git checkout "$ROLLBACK_TARGET"
NEW_COMMIT=$(git rev-parse HEAD)
echo "Now at commit: $NEW_COMMIT"

echo ""
echo "Step 4/5: Rebuilding Docker images..."
docker compose -f $DOCKER_COMPOSE_FILE build

echo ""
echo "Step 5/5: Starting services..."
if [ -f "$DOCKER_COMPOSE_PROD_FILE" ]; then
    docker compose -f $DOCKER_COMPOSE_FILE -f $DOCKER_COMPOSE_PROD_FILE up -d
else
    docker compose -f $DOCKER_COMPOSE_FILE up -d
fi

echo ""
echo "Waiting for services to start..."
sleep 30

echo ""
echo "Checking service status..."
FAILED=0
for service in mvp-traefik mvp-frontend mvp-backend mvp-postgres mvp-redis; do
    status=$(docker inspect --format='{{.State.Status}}' $service 2>/dev/null || echo "not found")
    if [ "$status" = "running" ]; then
        echo "  OK: $service"
    else
        echo "  ERROR: $service ($status)"
        FAILED=1
    fi
done

echo ""
echo "=========================================="
if [ $FAILED -eq 0 ]; then
    echo "Rollback completed successfully!"
    echo ""
    echo "Rolled back from: $CURRENT_COMMIT"
    echo "Now running:      $NEW_COMMIT"
    echo ""
    echo "To undo this rollback, run:"
    echo "  ./scripts/rollback.sh $CURRENT_COMMIT"
else
    echo "Rollback completed with errors!"
    echo "Some services may not be running correctly."
    echo "Check logs: docker compose logs"
fi
echo "=========================================="
