#!/bin/bash
set -e

# SSH setup
mkdir -p /root/.ssh
cp /ssh-keys/authorized_keys /root/.ssh/authorized_keys
chmod 700 /root/.ssh
chmod 600 /root/.ssh/authorized_keys
/usr/sbin/sshd

# IP forwarding is set via sysctls in docker-compose
iptables -P FORWARD ACCEPT

# Routing + egress NAT — depends on topology (detected by the presence of an
# isp-external interface).
ip route del default 2>/dev/null || true
if ip -o addr show | grep -q '203.0.113'; then
  # Direct-internet: fw-main has its own external (WAN) interface.
  ip route add default via 203.0.113.101
  # Egress NAT SCOPED to the external/WAN interface (the one with the public
  # 203.0.113.x address) — NOT a blanket MASQUERADE (ISS-0156). Scoping to the WAN
  # means inter-zone traffic (protected↔protected, protected↔internal) keeps its
  # source, so the dmz-resident resolver sees each client's real zone for
  # source-based DNS views. This boot-time rule is what target machines need for
  # egress/DNS BEFORE any module deploys; celilo's iptables module applies the
  # same WAN-scoped MASQUERADE on deploy (idempotent — the production code path).
  EXT_IFACE=$(ip -o addr show | awk '/203\.0\.113\./{print $2; exit}')
  iptables -t nat -A POSTROUTING -o "$EXT_IFACE" -j MASQUERADE
else
  # Two-layer: no external interface on fw-main; it routes outbound to the
  # upstream firewall (fw-isp) and MASQUERADEs toward it (egress leaves via the
  # internal-facing interface, so there is no single WAN interface to scope to).
  ip route add default via 10.226.1.1
  # Protected↔protected (the segmented zones ↔ each other) is NOT NAT'd — a real
  # firewall routes between its segmented zones without NAT, preserving the
  # client source so the dmz-resident resolver can serve source-based split-horizon
  # (ISS-0156). Only protected↔internal and egress get MASQUERADE'd below. Without
  # this RETURN, app→dmz and internal→dmz would both be SNAT'd to the dmz gateway
  # and become indistinguishable (confirmed via live probe).
  #
  # PROTECTED_SUBNETS is passed from the compose generator (ZONE_SUBNETS). It used
  # to be written as `-s 10.0.0.0/8 -d 10.0.0.0/8`, which meant "protected" only
  # because `internal` happened to be numbered out of 192.168/16 and every other
  # zone out of 10/8 — the firewall's NAT policy silently depended on the octets. With
  # the whole sim in 10.226.0.0/16 (#539) that shorthand would have swept `internal`
  # into the no-NAT class and handed LAN devices the protected DNS view.
  for src in ${PROTECTED_SUBNETS:?PROTECTED_SUBNETS not set by compose}; do
    for dst in ${PROTECTED_SUBNETS}; do
      iptables -t nat -A POSTROUTING -s "$src" -d "$dst" -j RETURN
    done
  done
  iptables -t nat -A POSTROUTING -j MASQUERADE
fi

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

echo "fw-main ready"
sleep infinity
