#!/bin/bash
#
# Restart the active Eagle instance.
# Reads the active instance from /opt/eagle0/.active-instance (set by deploy-blue-green.sh).
#
# This is useful when you need Eagle to reload game state from persistence
# (e.g., after a rewind) without doing a full blue-green deployment.
#
# Usage:
#   eagle-restart              # Restart active instance, wait for healthy
#   eagle-restart --no-wait    # Restart without waiting for health check
#
# To create an alias, add to ~/.bashrc:
#   alias eagle-restart='/opt/eagle0/scripts/eagle-restart.sh'
#

set -euo pipefail

APP_DIR="${APP_DIR:-/opt/eagle0}"
ACTIVE_FILE="${APP_DIR}/.active-instance"
HEALTH_TIMEOUT=120  # seconds

# Read active instance from file, with fallback
if [ -f "$ACTIVE_FILE" ]; then
    ACTIVE=$(cat "$ACTIVE_FILE")
else
    # Fallback: check which container is actually running
    if docker inspect --format='{{.State.Running}}' eagle-blue 2>/dev/null | grep -q true; then
        ACTIVE="eagle-blue"
    elif docker inspect --format='{{.State.Running}}' eagle-green 2>/dev/null | grep -q true; then
        ACTIVE="eagle-green"
    else
        ACTIVE=""
    fi
fi

if [ -z "$ACTIVE" ]; then
    echo "Error: No active Eagle instance found" >&2
    exit 1
fi

NO_WAIT=false
if [ "${1:-}" = "--no-wait" ]; then
    NO_WAIT=true
fi

echo "Restarting ${ACTIVE}..."
docker restart "$ACTIVE"

if [ "$NO_WAIT" = true ]; then
    echo "Restart initiated. Not waiting for health check."
    exit 0
fi

echo "Waiting for ${ACTIVE} to become healthy (timeout: ${HEALTH_TIMEOUT}s)..."
elapsed=0
while [ $elapsed -lt $HEALTH_TIMEOUT ]; do
    health=$(docker inspect --format='{{.State.Health.Status}}' "$ACTIVE" 2>/dev/null || echo "unknown")
    if [ "$health" = "healthy" ]; then
        echo "${ACTIVE} is healthy after ${elapsed}s."
        exit 0
    fi
    sleep 2
    elapsed=$((elapsed + 2))
    # Print progress every 10 seconds
    if [ $((elapsed % 10)) -eq 0 ]; then
        echo "  ...${elapsed}s (status: ${health})"
    fi
done

echo "Warning: ${ACTIVE} did not become healthy within ${HEALTH_TIMEOUT}s (status: ${health})" >&2
echo "Check logs with: eagle-logs" >&2
exit 1
