#!/bin/sh
# E2E test for scripts/rolling-upgrade.sh
#
# Runs inside a Docker container with the fafb-q binary available.
# Tests the full upgrade cycle: start server → drain → stop → install → restart → health.
#
# Usage: docker compose -f docker-compose.test.yml up e2e-upgrade
set -eu

BINARY="/app/fafb-q"
CONFIG="/app/tests/e2e/config-e2e.toml"
ADMIN_KEY="e2e-test-admin-key-minimum-24-chars"
ADMIN_URL="http://127.0.0.1:8080"
DATA_DIR="${FAFB_DATA_DIR:-/app/data}"

die() {
    echo "E2E FAIL: $1" >&2
    exit 1
}

# ── Setup: install dependencies ──────────────────────────────────────────────
# The runtime image is minimal; we need curl and procps (for pgrep).
echo "=== Installing dependencies ==="
apt-get update -qq && apt-get install -y -qq curl procps > /dev/null 2>&1

# ── Step 1: Start the server ─────────────────────────────────────────────────
echo "=== Starting fafb-q server ==="
mkdir -p "$DATA_DIR"
"$BINARY" serve --config "$CONFIG" &
server_pid=$!
echo "Server PID: $server_pid"

# Wait for /health/ready to return 200
echo "Waiting for server to become ready..."
waited=0
while [ "$waited" -lt 30 ]; do
    code=$(curl -s -o /dev/null -w '%{http_code}' --connect-timeout 2 "$ADMIN_URL/health/ready" 2>/dev/null) || true
    if [ "$code" = "200" ]; then
        break
    fi
    sleep 1
    waited=$((waited + 1))
done
if [ "$code" != "200" ]; then
    die "server did not become ready within 30s (last HTTP code: $code)"
fi
echo "Server ready."

# Verify --version works (prerequisite for the upgrade script smoke test)
version=$("$BINARY" --version 2>&1)
echo "Running version: $version"

# ── Step 2: Prepare a "new" binary ───────────────────────────────────────────
# Use the same binary — we're testing the orchestration, not a real version change.
new_binary="/tmp/fafb-q-new"
cp "$BINARY" "$new_binary"
chmod +x "$new_binary"

# ── Step 3: Run rolling-upgrade.sh ───────────────────────────────────────────
echo "=== Running rolling-upgrade.sh ==="
/app/scripts/rolling-upgrade.sh \
    --binary "$new_binary" \
    --admin-key "$ADMIN_KEY" \
    --admin-url "$ADMIN_URL" \
    --config "$CONFIG" \
    --drain-timeout 15

upgrade_exit=$?
if [ "$upgrade_exit" -ne 0 ]; then
    die "rolling-upgrade.sh exited with code $upgrade_exit"
fi

# ── Step 4: Verify the server is running ─────────────────────────────────────
echo "=== Verifying server after upgrade ==="

# Check /health/ready returns 200
final_code=$(curl -s -o /dev/null -w '%{http_code}' --connect-timeout 5 "$ADMIN_URL/health/ready") || true
if [ "$final_code" != "200" ]; then
    die "server not healthy after upgrade (HTTP $final_code)"
fi

# Verify a fafb-q process is running
if ! pgrep -x fafb-q > /dev/null 2>&1; then
    die "no fafb-q process running after upgrade"
fi

new_version=$("$BINARY" --version 2>&1)
echo "Server running after upgrade: $new_version"

echo ""
echo "=== E2E PASS: rolling-upgrade.sh completed successfully ==="
