#!/bin/sh
set -eu
# Own only these priorities/table; leave Tailscale and Docker routing intact.
table=20220
return_table=20221
cleanup() {
    for family in -4 -6; do
        for pref in 18990 19000 19010 19011; do
            while ip "$family" rule del pref "$pref" 2>/dev/null; do :; done
        done
        ip "$family" route flush table "$table" 2>/dev/null || true
        ip "$family" route flush table "$return_table" 2>/dev/null || true
    done
    for tool in iptables ip6tables; do
        for pair in 'eth0 mihomo0' 'mihomo0 eth0' 'tailscale0 mihomo0' 'mihomo0 tailscale0'; do
            set -- $pair
            while "$tool" -w -D FORWARD -i "$1" -o "$2" -m comment --comment mihomo-gateway -j ACCEPT 2>/dev/null; do :; done
        done
    done
}
case "${1:-}" in
down) cleanup ;;
up)
    cleanup
    sysctl -qw net.ipv6.conf.eth0.accept_ra=2
    sysctl -qw net.ipv4.ip_forward=1 net.ipv6.conf.all.forwarding=1
    sysctl -qw net.ipv4.conf.all.send_redirects=0 net.ipv4.conf.eth0.send_redirects=0
    ip -6 addr replace fda2:a01e:2cb2::168/64 dev eth0
    count=0
    until ip link show mihomo0 >/dev/null 2>&1; do
        count=$((count+1)); [ "$count" -lt 30 ] || exit 1; sleep 1
    done
    for tool in iptables ip6tables; do
        for pair in 'eth0 mihomo0' 'mihomo0 eth0' 'tailscale0 mihomo0' 'mihomo0 tailscale0'; do
            set -- $pair
            "$tool" -w -I FORWARD 1 -i "$1" -o "$2" -m comment --comment mihomo-gateway -j ACCEPT
        done
    done
    # Replies emitted by TUN return through AX9000, preserving symmetric conntrack.
    # Match only TUN ingress; Pi services, its outbound sockets and Tailnet stay unchanged.
    ip -4 route replace 192.168.32.0/24 via 192.168.32.1 dev eth0 onlink table "$return_table"
    ip -6 route replace fda2:a01e:2cb2::/64 via fda2:a01e:2cb2::1 dev eth0 onlink table "$return_table"
    for family in -4 -6; do
        ip "$family" rule add pref 18990 iif mihomo0 lookup "$return_table"
        ip "$family" route replace default dev mihomo0 table "$table"
        for ingress in eth0 tailscale0; do
            ip "$family" rule add pref 19000 iif "$ingress" lookup main suppress_prefixlength 0
            ip "$family" rule add pref 19010 iif "$ingress" ipproto tcp lookup "$table"
            ip "$family" rule add pref 19011 iif "$ingress" ipproto udp lookup "$table"
        done
    done
    ;;
*) exit 2 ;;
esac
