#!/bin/bash
# Rollback script for {{ project_name }}
# Generated by Prism
#
# Usage: ./rollback.sh [BACKUP_FILE]
#   BACKUP_FILE: Path to .env backup file (optional, uses most recent if not specified)

set -euo pipefail

# Configuration
PROJECT_NAME="{{ project_name }}"
APP_DIR="/opt/${PROJECT_NAME}"
COMPOSE_FILE="docker-compose.prod.yml"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] WARNING:${NC} $1"
}

error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ERROR:${NC} $1"
    exit 1
}

cd "${APP_DIR}" || error "Failed to change to ${APP_DIR}"

# Find backup file
if [ -n "${1:-}" ]; then
    BACKUP_FILE="$1"
else
    # Find most recent backup
    BACKUP_FILE=$(ls -t .env.backup.* 2>/dev/null | head -1)
fi

if [ -z "${BACKUP_FILE}" ] || [ ! -f "${BACKUP_FILE}" ]; then
    error "No backup file found. Cannot rollback."
fi

log "Rolling back to: ${BACKUP_FILE}"

# Extract the IMAGE_TAG from backup
ROLLBACK_TAG=$(grep "^IMAGE_TAG=" "${BACKUP_FILE}" | cut -d'=' -f2)

if [ -z "${ROLLBACK_TAG}" ]; then
    error "Could not find IMAGE_TAG in backup file"
fi

log "Rolling back to image tag: ${ROLLBACK_TAG}"

# Restore .env file
cp "${BACKUP_FILE}" .env
log "Restored .env from backup"

# Stop current containers
log "Stopping current containers..."
docker compose -f "${COMPOSE_FILE}" down --timeout 30 || warn "Some containers may not have stopped cleanly"

# Pull the rollback images (they should already be cached)
log "Pulling rollback images..."
docker compose -f "${COMPOSE_FILE}" pull || warn "Failed to pull images (may use cached)"

# Start containers with rollback version
log "Starting containers with rollback version..."
docker compose -f "${COMPOSE_FILE}" up -d --remove-orphans || error "Failed to start containers"

# Wait for health check
log "Waiting for application to be healthy..."
sleep 10

HEALTH_CHECK_URL="http://localhost/health"
MAX_RETRIES=30
RETRY_COUNT=0

while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
    if curl -sf "${HEALTH_CHECK_URL}" > /dev/null 2>&1; then
        log "Health check passed!"
        break
    fi
    RETRY_COUNT=$((RETRY_COUNT + 1))
    log "Waiting for application... (attempt ${RETRY_COUNT}/${MAX_RETRIES})"
    sleep 2
done

if [ $RETRY_COUNT -eq $MAX_RETRIES ]; then
    error "Health check failed after rollback"
fi

log "Rollback completed successfully!"
log "Application is now running version: ${ROLLBACK_TAG}"
