#!/bin/sh
set -eu

network_bridge() {
  id=$(docker network inspect -f '{{.Id}}' "$1")
  printf 'br-%.12s\n' "$id"
}

wait_network() {
  count=0
  until docker network inspect "$1" >/dev/null 2>&1; do
    count=$((count + 1))
    [ "$count" -lt 60 ] || return 1
    sleep 2
  done
}

install_rule() {
  network=$1 subnet=$2 gateway=$3 table=$4 priority=$5
  bridge=$(network_bridge "$network")
  ip rule del from "$subnet" table "$table" priority "$priority" 2>/dev/null || true
  ip rule add from "$subnet" table "$table" priority "$priority"
  # A fresh host has no FIB object for the custom table yet; iproute2 returns
  # an error in that perfectly normal case.
  ip route flush table "$table" 2>/dev/null || true
  ip route add "$subnet" dev "$bridge" scope link table "$table"
  ip route add default via "$gateway" dev "$bridge" table "$table"
}

wait_network mike-ai_frontend
wait_network mike-ai-tools-egress

# Preserve all east/west Docker communication before source-policy routing.
ip rule del to 172.30.0.0/16 lookup main priority 11000 2>/dev/null || true
ip rule add to 172.30.0.0/16 lookup main priority 11000

# The gateway's encrypted outer packets must leave through the host's normal
# uplink. Without these narrow exceptions they would match the source rules
# below and be routed straight back into the gateway (a routing loop).
ip rule del from 172.30.10.254/32 lookup main priority 11010 2>/dev/null || true
ip rule add from 172.30.10.254/32 lookup main priority 11010
ip rule del from 172.30.50.254/32 lookup main priority 11011 2>/dev/null || true
ip rule add from 172.30.50.254/32 lookup main priority 11011

install_rule mike-ai_frontend 172.30.10.0/24 172.30.10.254 51821 12010
install_rule mike-ai-tools-egress 172.30.50.0/24 172.30.50.254 51825 12050

# Drop any route/conntrack decisions learned before the policy rules existed.
# Compose will wait for the gateway healthcheck before exposing dependants.
if [ "$(docker inspect -f '{{.State.Running}}' mike-ai-wireguard-gateway 2>/dev/null || true)" = true ]; then
  docker restart mike-ai-wireguard-gateway >/dev/null
fi
