#!/bin/bash
# celilo-website-sim entrypoint.
#
# Serves https://celilo.computer/install.sh (and the rest of the static
# site under modules/celilo-website/site/dist/) with a Pebble-issued cert.
# Mirrors the isitup simulator's network bringup almost exactly.

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 443 never opens. fw-ext is per-test, so the route is
# unreachable when shared infra runs alone — harmless; the test brings
# fw-ext up before celilo.computer 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 this container trusts certs
# issued by Pebble (relevant if anything inside the container ever needs
# to dial back out over HTTPS to a Pebble-issued endpoint). 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

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