#!/usr/bin/env bash
# End-to-end check of the real binaries: deploys examples/node-app and walks
# through redeploy, stop/start/restart, failed builds, unhealthy releases,
# rollback and daemon restarts.
#
# Usage: scripts/e2e-smoke.sh            (uses target/debug)
#        BIN_DIR=target/release scripts/e2e-smoke.sh
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BIN_DIR="$(cd "${BIN_DIR:-$ROOT/target/debug}" && pwd)"
AEGIS_CLI="$BIN_DIR/aegis-cli"
AEGIS_DAEMON="$BIN_DIR/aegis-daemon"
GRPC_PORT="${GRPC_PORT:-50151}"
APP_PORT="${APP_PORT:-3456}"
WEB_PORT="${WEB_PORT:-18420}"
API="http://127.0.0.1:$WEB_PORT/api/v1"

WORK="$(mktemp -d)"
APP="$WORK/node-app"
DAEMON_LOG="$WORK/daemon.log"
DAEMON_PID=""

cleanup() {
  local code=$?
  if [ -n "$DAEMON_PID" ] && kill -0 "$DAEMON_PID" 2>/dev/null; then
    kill -TERM "$DAEMON_PID" 2>/dev/null || true
    wait "$DAEMON_PID" 2>/dev/null || true
  fi
  if [ "$code" -ne 0 ]; then
    echo "---- daemon log (last 60 lines) ----"
    tail -n 60 "$DAEMON_LOG" 2>/dev/null || true
    echo "FAILED (work dir kept at $WORK)"
  else
    rm -rf "$WORK"
  fi
}
trap cleanup EXIT

step() { printf '\n==> %s\n' "$*"; }
fail() { echo "ASSERTION FAILED: $*" >&2; exit 1; }
aegis() { (cd "$APP" && "$AEGIS_CLI" -c "$WORK/daemon.toml" "$@"); }

# Body of GET / from the app, or empty when nothing is listening.
app_body() { curl -sf --max-time 2 "http://127.0.0.1:$APP_PORT/" 2>/dev/null || true; }

expect_serving() {
  local want="$1"
  for _ in $(seq 1 50); do
    if app_body | grep -q "\"version\":\"$want\""; then return 0; fi
    sleep 0.2
  done
  fail "expected version $want to be served, got: $(app_body)"
}

expect_down() {
  for _ in $(seq 1 50); do
    if [ -z "$(app_body)" ]; then return 0; fi
    sleep 0.2
  done
  fail "expected the app to be down"
}

start_daemon() {
  # exec so that $! is the daemon itself, not a wrapping subshell.
  (cd "$WORK" && AEGIS_CONFIG="$WORK/daemon.toml" exec "$AEGIS_DAEMON" >>"$DAEMON_LOG" 2>&1) &
  DAEMON_PID=$!
  for _ in $(seq 1 100); do
    if "$AEGIS_CLI" -c "$WORK/daemon.toml" status >/dev/null 2>&1; then return 0; fi
    sleep 0.1
  done
  fail "daemon did not start"
}

stop_daemon() {
  kill -TERM "$DAEMON_PID"
  wait "$DAEMON_PID" 2>/dev/null || true
  DAEMON_PID=""
}

# JSON field from stdin, e.g. `... | json '["status"]'`.
json() { python3 -c "import sys, json; print(json.load(sys.stdin)$1)"; }

# curl with the API token (created once the daemon is up).
TOKEN=""
acurl() { curl -H "Authorization: Bearer $TOKEN" "$@"; }

api_post() {
  local body="${2:-}"
  [ -n "$body" ] || body='{}'
  acurl -sS -X POST -H 'Content-Type: application/json' -d "$body" "$API$1"
}

wait_http_deployment() {
  local id="$1" status=""
  for _ in $(seq 1 300); do
    status=$(acurl -sS "$API/deployments/$id" | json '["status"]')
    case "$status" in Queued|InProgress) sleep 0.2 ;; *) echo "$status"; return 0 ;; esac
  done
  fail "deployment $id did not finish"
}

set_version() {
  sed -i.bak "s/version: '[^']*'/version: '$1'/" "$APP/index.js" && rm -f "$APP/index.js.bak"
}

# ---------------------------------------------------------------------------
step "Preparing a copy of examples/node-app in $WORK"
cp -R "$ROOT/examples/node-app" "$APP"
# Tag responses with a version so we can tell releases apart.
sed -i.bak "s/status: 'ok'/status: 'ok', version: 'v1'/" "$APP/index.js" && rm -f "$APP/index.js.bak"
cat >"$WORK/daemon.toml" <<EOF
[daemon]
host = "127.0.0.1"
port = $GRPC_PORT
database_path = "$WORK/aegis.db"
log_level = "info"
data_dir = "$WORK/data"

[web]
enabled = true
host = "127.0.0.1"
port = $WEB_PORT

[update]
check = false               # no requests to GitHub from tests
EOF

step "Starting daemon"
start_daemon

step "aegis init + validate"
aegis init --name smoke-app
sed -i.bak "s/3000/$APP_PORT/g" "$APP/aegis.toml" && rm -f "$APP/aegis.toml.bak"
aegis validate

step "First deploy"
aegis deploy --release v1
expect_serving v1
aegis list | tee "$WORK/list.txt"
grep -q "smoke-app.*Running.*v1" "$WORK/list.txt" || fail "list does not show smoke-app running v1"
aegis logs -n 20 | grep -q "running on port $APP_PORT" || fail "app output missing from logs"

step "Restart changes the pid and keeps serving"
PID_BEFORE=$(aegis list | awk '/smoke-app/ {print $5}')
aegis restart
expect_serving v1
PID_AFTER=$(aegis list | awk '/smoke-app/ {print $5}')
[ "$PID_BEFORE" != "$PID_AFTER" ] || fail "restart did not change the pid ($PID_BEFORE)"

step "Stop and start"
aegis stop
expect_down
aegis start
expect_serving v1

step "Second deploy (v2)"
set_version v2
aegis deploy --release v2
expect_serving v2

step "Broken build is rejected and v2 keeps serving"
cp "$APP/package.json" "$WORK/package.json.good"
sed -i.bak 's/"build": "[^"]*"/"build": "echo compile error \&\& exit 1"/' "$APP/package.json"
if aegis deploy --release v3-broken-build >"$WORK/out.txt" 2>&1; then
  cat "$WORK/out.txt"; fail "broken build deployed successfully"
fi
cat "$WORK/out.txt"
grep -q "live release was not changed" "$WORK/out.txt" || fail "missing 'not changed' message"
grep -q "compile error" "$WORK/out.txt" || fail "build output not shown"
expect_serving v2
cp "$WORK/package.json.good" "$APP/package.json"

step "Unhealthy release is rolled back automatically"
sed -i.bak 's/"start": "[^"]*"/"start": "node missing.js"/' "$APP/package.json"
if aegis deploy --release v3-crashes >"$WORK/out.txt" 2>&1; then
  cat "$WORK/out.txt"; fail "crashing release deployed successfully"
fi
cat "$WORK/out.txt"
grep -q "release v2 is serving again" "$WORK/out.txt" || fail "missing rollback message"
expect_serving v2
cp "$WORK/package.json.good" "$APP/package.json"

step "Manual rollback to the previous release"
aegis rollback
expect_serving v1
aegis releases
aegis deployments
aegis timeline -n 15

step "Daemon restart brings the app back"
stop_daemon
expect_down
start_daemon
expect_serving v1

step "A stopped app stays stopped across daemon restarts"
aegis stop
expect_down
stop_daemon
start_daemon
sleep 1
[ -z "$(app_body)" ] || fail "stopped app came back after daemon restart"
aegis start
expect_serving v1

step "HTTP API: authentication"
code=$(curl -s -o /dev/null -w '%{http_code}' "$API/status")
[ "$code" = 401 ] || fail "unauthenticated request allowed ($code)"
[ "$(curl -s "http://127.0.0.1:$WEB_PORT/healthz")" = ok ] || fail "healthz"
PASSWORD=$(cat "$WORK/data/initial-admin-password")
[ "$(stat -c %a "$WORK/data/initial-admin-password" 2>/dev/null || stat -f %Lp "$WORK/data/initial-admin-password")" = 600 ] \
  || fail "initial password file is not private"
CSRF=$(curl -sS -c "$WORK/jar" -H 'Content-Type: application/json' \
  -d "{\"username\":\"admin\",\"password\":\"$PASSWORD\"}" "$API/auth/login" | json '["csrf_token"]')
code=$(curl -s -o /dev/null -w '%{http_code}' -b "$WORK/jar" -X PUT -H 'Content-Type: application/json' \
  -d '{"hour":1}' "$API/projects/smoke-app/schedule")
[ "$code" = 403 ] || fail "session request without CSRF token allowed ($code)"
TOKEN=$(curl -sS -b "$WORK/jar" -H "X-CSRF-Token: $CSRF" -H 'Content-Type: application/json' \
  -d '{"name":"e2e","scope":"deploy"}' "$API/tokens" | json '["token"]')
case "$TOKEN" in aegis_*) ;; *) fail "token creation failed" ;; esac
READ_TOKEN=$(AEGIS_CONFIG="$WORK/daemon.toml" "$AEGIS_DAEMON" admin create-token --name e2e-read --scope read)
code=$(curl -s -o /dev/null -w '%{http_code}' -H "Authorization: Bearer $READ_TOKEN" \
  -X POST -H 'Content-Type: application/json' -d '{}' "$API/processes/smoke-app/stop")
[ "$code" = 403 ] || fail "read-only token could stop an app ($code)"
expect_serving v1

step "HTTP API: status, guard rules and OpenAPI"
acurl -sSf "$API/status" | json '["project_count"]' | grep -qx 1 || fail "status via HTTP"
aegis status | grep -q "HTTP API:    http://127.0.0.1:$WEB_PORT/api/v1" || fail "CLI status lacks the API URL"
code=$(curl -s -o /dev/null -w '%{http_code}' -H 'Host: evil.example' "$API/status")
[ "$code" = 403 ] || fail "foreign Host header allowed ($code)"
code=$(acurl -s -o /dev/null -w '%{http_code}' -X POST -H 'Content-Type: text/plain' -d '{}' "$API/processes/smoke-app/stop")
[ "$code" = 415 ] || fail "non-JSON POST allowed ($code)"
expect_serving v1
acurl -sSf "$API/openapi.json" | json '["openapi"]' | grep -q '^3' || fail "openapi.json"

step "HTTP API: deploy with live event stream"
acurl -sN --max-time 120 "$API/events/stream?project=smoke-app" >"$WORK/sse.txt" &
SSE_PID=$!
sleep 0.5
set_version v5
DEP=$(api_post /projects/smoke-app/deploy '{"version":"v5-http"}' | json '["deployment_id"]')
[ "$(wait_http_deployment "$DEP")" = Success ] || fail "HTTP deploy failed"
expect_serving v5
sleep 0.5
grep -q "event: DeploymentCompleted" "$WORK/sse.txt" || fail "SSE stream missed DeploymentCompleted"
grep -q "event: BuildStageInstall" "$WORK/sse.txt" || fail "SSE stream missed build stages"

step "HTTP API: process control, logs and rollback"
[ "$(api_post /processes/smoke-app/restart | json '["status"]')" = Running ] || fail "HTTP restart"
expect_serving v5
acurl -sSf "$API/processes/smoke-app/logs?lines=20" | grep -q "running on port $APP_PORT" || fail "HTTP logs"
[ "$(api_post /projects/smoke-app/rollback | json '["version"]')" = v1 ] || fail "HTTP rollback"
expect_serving v1
acurl -sS -X PUT -H 'Content-Type: application/json' -d '{"hour":3,"minute":30}' "$API/projects/smoke-app/schedule" \
  | json '["schedule"]["hour"]' | grep -qx 3 || fail "HTTP schedule"

step "CLI: delete an app"
if aegis delete smoke-app </dev/null >"$WORK/out.txt" 2>&1; then
  fail "delete without --yes outside a terminal was not refused"
fi
expect_serving v1
aegis delete smoke-app --yes | tee "$WORK/out.txt"
grep -q "Deleted smoke-app" "$WORK/out.txt" || fail "aegis delete output"
expect_down
aegis list | grep -q smoke-app && fail "deleted app still listed"
[ ! -d "$WORK/data/projects" ] || [ -z "$(ls -A "$WORK/data/projects")" ] || fail "release directories left behind"
acurl -sS "$API/events?limit=1000" | grep -q '"event_type":"ProjectDeleted"' || fail "ProjectDeleted not recorded"

step "Daemon shutdown is not held up by an open event stream"
kill -0 "$SSE_PID" 2>/dev/null || fail "SSE client ended early"
START=$(date +%s)
stop_daemon
ELAPSED=$(( $(date +%s) - START ))
[ "$ELAPSED" -lt 20 ] || fail "shutdown took ${ELAPSED}s with an open stream"
for _ in $(seq 1 25); do kill -0 "$SSE_PID" 2>/dev/null || break; sleep 0.2; done
if kill -0 "$SSE_PID" 2>/dev/null; then fail "SSE stream still open after shutdown"; fi

step "Unsafe configurations are refused"
refuse() {
  local name="$1" extra="$2"
  printf '[daemon]\nhost = "%s"\nport = %s\ndatabase_path = "%s/refused.db"\ndata_dir = "%s/refused"\n[web]\nenabled = true\nport = 18499\n%b\n' \
    "${3:-127.0.0.1}" "$GRPC_PORT" "$WORK" "$WORK" "$extra" >"$WORK/unsafe.toml"
  if AEGIS_CONFIG="$WORK/unsafe.toml" "$AEGIS_DAEMON" check-config >/dev/null 2>&1; then
    fail "check-config accepted: $name"
  fi
  if AEGIS_CONFIG="$WORK/unsafe.toml" timeout 10 "$AEGIS_DAEMON" run >/dev/null 2>&1; then
    fail "daemon started with: $name"
  fi
}
refuse "public HTTP bind without TLS" 'host = "0.0.0.0"\nallowed_hosts = ["a.example"]'
refuse "proxy mode without allowed_hosts" 'behind_proxy = true'
refuse "TLS with only a certificate" 'host = "0.0.0.0"\nallowed_hosts = ["a.example"]\n[web.tls]\ncert_path = "/x.pem"'
refuse "gRPC on a public address" '' 0.0.0.0
if curl -s --max-time 2 "http://127.0.0.1:18499/healthz" >/dev/null 2>&1; then
  fail "something is listening on the refused port"
fi

printf '\nAll end-to-end checks passed.\n'
