#!/bin/bash
# Observer vantage setup (ISS-0117).
#
# Installs the routing profile that makes this container a FAITHFUL vantage — the
# load-bearing part of the framework. A vantage's correctness is its routing table:
# an internalDevice must reach a fronted service only via the firewall natIp, never a
# segmented-zone container IP directly. Driven by env from the compose generator:
#   OBSERVER_GATEWAY   - default route (the home router for internalDevice, the zone
#                        firewall for dmz/app/secure, fw-ext for publicInternet)
#   OBSERVER_INTERZONE - "1" to add the management-style explicit inter-zone routes
#                        (the all-VLAN trap). "0" for every faithful consumer vantage.
#   OBSERVER_RESOLVERS - space-separated nameservers for /etc/resolv.conf, in order
set -u

GATEWAY="${OBSERVER_GATEWAY:?OBSERVER_GATEWAY is required}"
INTERZONE="${OBSERVER_INTERZONE:-0}"
RESOLVERS="${OBSERVER_RESOLVERS:-203.0.113.1}"

echo "Observer starting: gateway=${GATEWAY} interzone=${INTERZONE} resolvers='${RESOLVERS}'"

# --- Default route ---
# Docker seeds a default via the network's own gateway; replace it with the gateway a
# real device at this location would use.
ip route del default 2>/dev/null || true
ip route add default via "${GATEWAY}"

# --- Inter-zone routes (the management trap; only when explicitly requested) ---
# A real consumer vantage NEVER has these — that is the whole point. Present only so a
# `management`-style all-VLAN box can be modelled deliberately.
if [ "${INTERZONE}" = "1" ]; then
  ip route add 10.226.10.0/24 via 10.226.1.254 2>/dev/null || true  # dmz via fw-main
  ip route add 10.226.20.0/24 via 10.226.1.254 2>/dev/null || true  # app via fw-main
  ip route add 10.226.30.0/24 via 10.226.1.254 2>/dev/null || true  # secure via fw-main
fi

# --- Resolver ---
: > /etc/resolv.conf
for ns in ${RESOLVERS}; do
  echo "nameserver ${ns}" >> /etc/resolv.conf
done

# --- Pebble runtime ACME root CA ---
# Pebble mints a fresh root each startup, so the build-time CA can't verify certs Caddy
# obtained at runtime. Fetch the live root so curl/openssl can validate real chains —
# the no-self-signed / CA-provenance assertions depend on a correct trust store.
echo "Fetching Pebble ACME root CA..."
for _ in $(seq 1 30); 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

echo "Observer ready: $(hostname)"
ip route
sleep infinity
