#!/bin/bash
set -e

# Routing
ip route del default 2>/dev/null || true
# Default route via real-internet bridge (for Squid outbound to real internet)
ip route add default via 172.30.0.1
# Internal subnets via fw-isp
ip route add 10.226.1.0/24 via 203.0.113.100     # Internal via fw-isp
ip route add 10.226.10.0/24 via 203.0.113.100       # dmz via fw-isp
ip route add 10.226.20.0/24 via 203.0.113.100       # app via fw-isp
ip route add 10.226.30.0/24 via 203.0.113.100       # secure via fw-isp

# IP forwarding is set via sysctls in docker-compose

# NAT/forward between isp-external and internet-external.
#
# The customer's public /24 is ROUTED, never re-NAT'd. An ISP does not NAT a
# subscriber that already holds a public address — the whole point of
# 203.0.113.100 is that it IS the customer's address on the internet. fw-ext
# used to MASQUERADE it anyway, so every packet leaving the fleet reached the
# public simulators bearing fw-ext's own 100.64.0.1.
#
# That is not cosmetic. Namecheap-style DDNS registers the SOURCE address of
# the update when the caller omits `ip=` (which is now how celilo registers
# public names — #464/#466), so the double NAT published 100.64.0.1 for every
# public hostname: an address that DNATs to nothing, breaking ACME validation
# and any inbound reach. It also silently clobbered seeded apex records.
# Anything that reasons about "the address the internet sees us as" was
# measuring the simulator's own artefact.
iptables -t nat -A POSTROUTING -s 203.0.113.0/24 -j RETURN
iptables -t nat -A POSTROUTING -j MASQUERADE
iptables -P FORWARD ACCEPT

# Start Squid transparent proxy (runs on fw-ext itself)
rm -f /run/squid.pid
# Complete the cache swap directories before starting. The image's build-time
# `squid -z` (Dockerfile.router) is killed after a fixed `sleep 1`, which can
# interrupt it and leave an INCOMPLETE L1/L2 set (observed: 00–0C present,
# 0D–0F missing). `squid -N` then FATALs ("Failed to verify one of the swap
# directories") and never binds — so the transparent-proxy REDIRECT below sends
# every apt fetch to a closed port and target deploys fail with intermittent,
# non-warming "connection refused" (e.g. knot's `apt install`). `squid -z` is
# idempotent, so running it here guarantees a complete tree. `--foreground` is
# REQUIRED: a bare `squid -z` daemonizes and lingers (holding /run/squid.pid),
# so the following `squid -N` would FATAL "Squid is already running"; with
# --foreground, -z runs synchronously, removes the pid file, and exits clean.
squid --foreground -z -f /etc/squid/squid.conf
rm -f /run/squid.pid
squid -N -f /etc/squid/squid.conf &

# Wait for Squid to be listening on both 3128 (HTTP) and 3129 (HTTPS)
# BEFORE installing iptables NAT rules. Without this gate, target
# containers boot, hit the NAT redirect, and get "connection refused"
# from a not-yet-listening Squid — which apt-get treats as a partial
# fetch failure (lists end up missing universe), making downstream
# package installs fail with "No package matching 'X' is available".
echo "Waiting for Squid to bind 3128/3129..."
for i in $(seq 1 60); do
  if (echo >/dev/tcp/127.0.0.1/3128) 2>/dev/null && (echo >/dev/tcp/127.0.0.1/3129) 2>/dev/null; then
    echo "Squid ready (attempt $i)"
    break
  fi
  sleep 1
done

# Transparent proxy: REDIRECT HTTP/HTTPS from isp-external to local Squid
# Exception: traffic to simulated services (100.64.0.0/24) passes through directly
ISP_IFACE=$(ip -o addr show | grep '203.0.113.101' | awk '{print $2}')
iptables -t nat -A PREROUTING -i "$ISP_IFACE" -p tcp --dport 80 ! -d 100.64.0.0/24 -j REDIRECT --to-port 3128
iptables -t nat -A PREROUTING -i "$ISP_IFACE" -p tcp --dport 443 ! -d 100.64.0.0/24 -j REDIRECT --to-port 3129

# 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)
# Retry until Pebble is up and responding
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
) &

echo "fw-ext ready (with transparent HTTPS proxy)"
sleep infinity
