#!/bin/sh

ip rule add fwmark 1 table 100 2>/dev/null || true
ip route add local default dev lo table 100 2>/dev/null || true
ip rule add fwmark 2 table main priority 100 2>/dev/null || true

nft add table inet sing-box 2>/dev/null || true
nft flush table inet sing-box

# prerouting
nft add chain inet sing-box prerouting '{ type filter hook prerouting priority mangle; policy accept; }'
nft add rule inet sing-box prerouting iifname != "br-lan" accept
nft add rule inet sing-box prerouting ct mark 0x01 accept
nft add rule inet sing-box prerouting meta mark 0x02 accept
nft add rule inet sing-box prerouting ip daddr { 10.0.0.0/8, 127.0.0.0/8, 169.254.0.0/16, 172.16.0.0/12, 192.168.0.0/16, 224.0.0.0/4, 240.0.0.0/4 } accept
nft add rule inet sing-box prerouting meta l4proto { tcp, udp } tproxy to :7893 meta mark set 0x01

# output：所有 root 进程流量打 mark 2 直连
nft add chain inet sing-box output '{ type route hook output priority mangle; policy accept; }'
nft add rule inet sing-box output ip daddr { 10.0.0.0/8, 127.0.0.0/8, 169.254.0.0/16, 172.16.0.0/12, 192.168.0.0/16, 224.0.0.0/4, 240.0.0.0/4 } accept
nft add rule inet sing-box output meta mark 0x02 accept
nft add rule inet sing-box output meta skuid 0 meta mark set 0x02
