#!/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

# Routing
ip route del default 2>/dev/null || true
ip route add default via 203.0.113.101            # Internet via fw-ext
ip route add 10.226.10.0/24 via 10.226.1.254       # dmz via fw-main
ip route add 10.226.20.0/24 via 10.226.1.254       # app via fw-main
ip route add 10.226.30.0/24 via 10.226.1.254       # secure via fw-main

# IP forwarding is set via sysctls in docker-compose

# NAT all outbound traffic
iptables -t nat -A POSTROUTING -j MASQUERADE
iptables -P FORWARD ACCEPT

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

# Start dnsmasq DHCP server on internal network.
#
# Skippable, because celilo can serve DHCP itself (`modules/dnsmasq-dhcp`) and
# two DHCP servers on one broadcast domain race: whichever answers a DISCOVER
# first wins, and a test asserting which one served a lease would be asserting
# a coin toss. An operator moving DHCP to celilo turns the router's off, so a
# suite that tests celilo's DHCP models that by setting ROUTER_DHCP=off.
if [ "${ROUTER_DHCP:-on}" = "off" ]; then
  echo "dnsmasq DHCP server NOT started (ROUTER_DHCP=off; celilo serves DHCP here)"
else
  dnsmasq --conf-dir=/etc/dnsmasq.d --keep-in-foreground --log-facility=- &
  echo "dnsmasq DHCP server started"
fi

# Start greenwave simulator
if [ -f /simulator/server.ts ]; then
  cd /simulator && bun run server.ts &
fi

echo "fw-isp ready"
sleep infinity
