#!/bin/bash
#
# SOCKS proxy startup. Configures routing + DNS for the chosen vantage,
# then exec's dante-server. Requires --cap-add NET_ADMIN on `docker run`
# so we can rewrite the routing table.
set -e

VANTAGE="${VANTAGE:-isp-external}"

case "$VANTAGE" in
  isp-external)
    # Residential-user view. Default route via fw-ext (.101) which DNATs
    # public-internet traffic into the dmz (caddy at 10.226.10.10). DNS via
    # comcast-resolver (.1) which walks the root → TLD → namecheap chain.
    GATEWAY="203.0.113.101"
    NAMESERVER="203.0.113.1"
    ;;
  internal)
    # Operator-on-LAN view. Default route via fw-isp (.1); split-horizon
    # resolver at .10 returns the firewall's same-subnet NAT IP for the
    # test domain, which DNATs to caddy.
    GATEWAY="10.226.1.1"
    NAMESERVER="10.226.1.10"
    ;;
  *)
    echo "Unknown VANTAGE: $VANTAGE (expected isp-external or internal)" >&2
    exit 1
    ;;
esac

# Replace docker's IPAM-default gateway (which has no router listening)
# with the actual zone gateway. del-then-add is idempotent against a
# possibly-missing prior default route.
ip route del default 2>/dev/null || true
ip route add default via "$GATEWAY"

# An explicit resolver from the caller wins over the vantage default. The proxy
# is what resolves names for a SOCKS5 client — a browser hands it the hostname
# and never resolves it itself — so a test driving a browser at a name only the
# fleet's own resolver knows has to say so here. Modelling a real device: one
# on the internal zone is handed the fleet's resolver, not a fixed stub.
NAMESERVER="${NAMESERVER_OVERRIDE:-$NAMESERVER}"

# Bypass docker's embedded resolver — point directly at the in-network
# DNS so split-horizon and the namecheap simulator both behave correctly.
echo "nameserver $NAMESERVER" > /etc/resolv.conf

echo "socks-proxy ready: vantage=$VANTAGE gateway=$GATEWAY dns=$NAMESERVER" >&2

exec /usr/sbin/danted -f /etc/danted.conf
