#!/bin/bash
# E2E target machine boot setup: routing, DNS, SSH keys.
# Runs as a systemd oneshot service at boot.
# GATEWAY is set via environment variable from docker-compose.
set -e

GATEWAY="${GATEWAY:?GATEWAY not set}"

# Wait for SSH keys (management container generates them)
echo "Waiting for SSH keys..."
for i in $(seq 1 30); do
  if [ -f /ssh-keys/authorized_keys ]; then
    break
  fi
  sleep 1
done

if [ ! -f /ssh-keys/authorized_keys ]; then
  echo "ERROR: SSH keys not found after 30s"
  exit 1
fi

# SSH keys
mkdir -p /root/.ssh
cp /ssh-keys/authorized_keys /root/.ssh/authorized_keys
chmod 700 /root/.ssh
chmod 600 /root/.ssh/authorized_keys

# Routing
ip route del default 2>/dev/null || true
ip route add default via "$GATEWAY"

# DNS
echo "nameserver 203.0.113.1" > /etc/resolv.conf

# Fetch Pebble's runtime ACME root CA (Pebble generates a fresh root
# at each startup; the static pebble-ca.crt baked into the image only
# signs Pebble's own API). Without this, deployed apps that need to
# verify peer TLS certs issued by Pebble (e.g. forgejo's OIDC
# auto-discovery hitting authentik through caddy) fail with
# "certificate signed by unknown authority".
#
# BACKGROUNDED to keep target-setup's wall-clock low — the cele2e
# harness only waits 60s for `systemctl is-active target-setup`, and
# foreground curl+update-ca-certificates adds ~8s which (combined
# with apt-cache pre-warm below) pushes total boot to ~47s. With
# baseline dockerd init at 25-35s, that's right against the budget
# and intermittently exceeds it. Background here is safe because
# Ansible doesn't reach OIDC-validating steps for several minutes
# after SSH-ready; the fetch loop has finished long before. Mirrors
# the equivalent block in fw-ext-routes.sh.
(
  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
) &

# NOTHING BELOW MAY DEPEND ON EGRESS. Readiness is gated on this script
# (`systemctl is-active target-setup`, 60s), and this script runs the moment the
# container does — BEFORE fw-ext has installed its NAT. Until it does, a packet
# for the real internet is not refused, it is blackholed, so anything fetched
# here pays a full connect timeout rather than failing fast.
#
# This used to pre-warm the apt cache, whose sources include dl.cloudsmith.io:
# four IPs, each timing out, 64s against a 60s budget. Measured both ways on a
# live stack — from a converged target that same fetch is 302 in 0.19s; with
# fw-ext's NAT flushed it hangs past 70s. So the failure was never a slow CDN or
# a broken simulator, which is exactly what "Timeout waiting for caddy
# target-setup" sent everyone looking for, twice in one day.
#
# The apt lists it was warming are now populated at IMAGE BUILD time (see
# docker/Dockerfile.target-*): Ansible still gets complete indexes on first
# connect, and readiness no longer races the firewall. Egress itself is
# untouched — the topology still NATs out, and pebble/apt still use it at deploy
# time, by which point the firewall has long converged. See #560.

echo "Target machine ready: $(hostname)"
