#!/bin/bash
# Start the Bun API server in the background, then Caddy in the foreground.
# Caddy terminates TLS (with a cert issued by Pebble) and reverse-proxies
# /api.json to Bun on localhost:8080.

set -e

# Route through fw-ext so we can reach comcast-resolver on isp-external
# (Docker's default bridge gateway has no path across networks). Without
# this, DNS for acme-v02.api.letsencrypt.org fails, Caddy never gets its
# cert, and port 443 never opens. Mirrors config/routing/pebble-startup.sh.
# fw-ext is a per-test container so this route is unreachable when shared
# infra runs alone — harmless; the test brings fw-ext up before the prober
# is exercised.
ip route del default 2>/dev/null || true
ip route add default via 100.64.0.1

# Fetch Pebble's runtime ACME root CA so the simulator trusts certs presented
# by the targets it probes (e.g. Caddy on iamtheinternet.org uses a Pebble-
# issued cert). Pebble regenerates its root on every startup, so the static
# pebble-ca.crt baked in at build time isn't enough.
echo "Waiting for Pebble ACME root CA..."
for i in $(seq 1 60); do
  if curl -sk https://100.64.0.100:15000/roots/0 -o /usr/local/share/ca-certificates/pebble-acme-root.crt 2>/dev/null; then
    if [ -s /usr/local/share/ca-certificates/pebble-acme-root.crt ]; then
      update-ca-certificates 2>/dev/null
      echo "Pebble ACME root CA installed"
      break
    fi
  fi
  sleep 2
done

cd /simulator
bun run server.ts &
BUN_PID=$!

# Wait briefly for Bun to come up before Caddy starts proxying
for i in $(seq 1 10); do
  if curl -sf http://127.0.0.1:8080/health >/dev/null 2>&1; then
    break
  fi
  sleep 0.3
done

# Caddy runs in foreground so the container lifecycle follows it
exec caddy run --config /etc/caddy/Caddyfile --adapter caddyfile
