#!/bin/sh
# Bananarchy Linux — Privacy Center Service & Routing Controller
# Manages Tor, GS-Warp, OpenVPN, GSocket (single TCP port), and WireGuard
# with zero background CPU/battery drain when services are turned off.
set -u

STATE_DIR="/tmp/bananarchy-privacy"
USER_HOME="/home/user"
CONF_DIR="$USER_HOME/.config/bananarchy"
CONF_FILE="$CONF_DIR/privacy.conf"
DEFAULT_GSWARP_OVPN="$USER_HOME/.config/gs-warp/client.ovpn"
if [ ! -f "$DEFAULT_GSWARP_OVPN" ] && [ -f "/etc/gs-warp/client.ovpn" ]; then
  DEFAULT_GSWARP_OVPN="/etc/gs-warp/client.ovpn"
fi

CMD="${1:-status}"

# Block all operations except stop-all when in duress mode or screen locked
if [ "$CMD" != "stop-all" ] && [ "$CMD" != "_ovpn_up" ] && [ "$CMD" != "_tor_up" ]; then
  if [ -e "/tmp/bananarchy_duress_mode" ] || [ -e "/tmp/bananarchy_screen_locked" ]; then
    echo "Error: Privacy Center is unavailable." >&2
    exit 1
  fi
fi

# Escalate to root via doas or bananarchy-engmenu-exec if invoked as normal user
if [ "$(id -u)" -ne 0 ]; then
  if command -v doas >/dev/null 2>&1; then
    exec doas -n /usr/bin/bananarchy-privacy-ctl "$@"
  elif [ -x /usr/bin/bananarchy-engmenu-exec ]; then
    ESCAPED=""
    for arg in "$@"; do
      ESCAPED="$ESCAPED '$(printf "%s" "$arg" | sed "s/'/'\\\\''/g")'"
    done
    exec /usr/bin/bananarchy-engmenu-exec --exec "/usr/bin/bananarchy-privacy-ctl $ESCAPED"
  fi
  echo "Error: root privileges required." >&2
  exit 1
fi

export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
mkdir -p "$STATE_DIR" "$CONF_DIR"

# Default configuration values
TOR_NATIVE=0
TOR_TETHER=0

GSWARP_NATIVE=0
GSWARP_TETHER=0
GSWARP_OVPN="$DEFAULT_GSWARP_OVPN"
GSWARP_SECRET=""

OVPN_NATIVE=0
OVPN_TETHER=0
OVPN_CONFIG="$DEFAULT_GSWARP_OVPN"

GSOCKET_NATIVE=0
GSOCKET_TETHER=0
GSOCKET_SECRET=""
GSOCKET_PORT="1080"
GSOCKET_MODE="client"

WG_NATIVE=0
WG_TETHER=0
WG_PRIVKEY=""
WG_PUBKEY=""
WG_PEER_PUBKEY=""
WG_PSK=""
WG_ENDPOINT=""
WG_ADDRESS="10.66.66.2/32"
WG_DNS="1.1.1.1"

load_conf() {
  if [ -f "$CONF_FILE" ]; then
    while IFS= read -r line; do
      case "$line" in
        *=*)
          k="${line%%=*}"
          v="${line#*=}"
          ;;
        *)
          continue
          ;;
      esac
      case "$k" in
        TOR_NATIVE|TOR_TETHER|GSWARP_NATIVE|GSWARP_TETHER|GSWARP_OVPN|GSWARP_SECRET|\
        OVPN_NATIVE|OVPN_TETHER|OVPN_CONFIG|GSOCKET_NATIVE|GSOCKET_TETHER|GSOCKET_SECRET|\
        GSOCKET_PORT|GSOCKET_MODE|WG_NATIVE|WG_TETHER|WG_PRIVKEY|WG_PUBKEY|WG_PEER_PUBKEY|\
        WG_PSK|WG_ENDPOINT|WG_ADDRESS|WG_DNS)
          eval "$k=\$v"
          ;;
      esac
    done < "$CONF_FILE"
  fi
  if [ -z "$GSWARP_OVPN" ] || [ ! -f "$GSWARP_OVPN" ]; then
    GSWARP_OVPN="$DEFAULT_GSWARP_OVPN"
  fi
  if [ -z "$GSWARP_SECRET" ] && [ -f "$GSWARP_OVPN" ]; then
    GSWARP_SECRET="$(md5sum "$GSWARP_OVPN" 2>/dev/null | awk '{print $1}')"
  fi
  if [ -z "$GSOCKET_SECRET" ]; then
    GSOCKET_SECRET="$GSWARP_SECRET"
  fi
  if [ -n "$WG_PRIVKEY" ] && [ -z "$WG_PUBKEY" ] && command -v wg >/dev/null 2>&1; then
    WG_PUBKEY="$(printf "%s\n" "$WG_PRIVKEY" | wg pubkey 2>/dev/null || true)"
  fi
}

save_conf() {
  mkdir -p "$CONF_DIR"
  cat > "$CONF_FILE.tmp" <<EOF
TOR_NATIVE=$TOR_NATIVE
TOR_TETHER=$TOR_TETHER
GSWARP_NATIVE=$GSWARP_NATIVE
GSWARP_TETHER=$GSWARP_TETHER
GSWARP_OVPN=$GSWARP_OVPN
GSWARP_SECRET=$GSWARP_SECRET
OVPN_NATIVE=$OVPN_NATIVE
OVPN_TETHER=$OVPN_TETHER
OVPN_CONFIG=$OVPN_CONFIG
GSOCKET_NATIVE=$GSOCKET_NATIVE
GSOCKET_TETHER=$GSOCKET_TETHER
GSOCKET_SECRET=$GSOCKET_SECRET
GSOCKET_PORT=$GSOCKET_PORT
GSOCKET_MODE=$GSOCKET_MODE
WG_NATIVE=$WG_NATIVE
WG_TETHER=$WG_TETHER
WG_PRIVKEY=$WG_PRIVKEY
WG_PUBKEY=$WG_PUBKEY
WG_PEER_PUBKEY=$WG_PEER_PUBKEY
WG_PSK=$WG_PSK
WG_ENDPOINT=$WG_ENDPOINT
WG_ADDRESS=$WG_ADDRESS
WG_DNS=$WG_DNS
EOF
  mv -f "$CONF_FILE.tmp" "$CONF_FILE"
  chown -R 10000:10000 "$CONF_DIR" 2>/dev/null || true
  chmod 0600 "$CONF_FILE" 2>/dev/null || true
}

ensure_netfilter_modules() {
  for mod in iptable_nat iptable_filter iptable_mangle xt_REDIRECT xt_MASQUERADE xt_mark xt_owner tun wireguard; do
    modprobe "$mod" 2>/dev/null || true
  done
}

get_tor_uid() {
  awk -F: '/^tor:/ {print $3; exit}' /etc/passwd 2>/dev/null || echo "109"
}

get_openvpn_gid() {
  awk -F: '/^openvpn:/ {print $3; exit}' /etc/group 2>/dev/null || echo "113"
}

is_tor_active() {
  if [ -f "$STATE_DIR/tor.pid" ]; then
    pid="$(cat "$STATE_DIR/tor.pid" 2>/dev/null || true)"
    if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
      return 0
    fi
  fi
  pgrep -x tor >/dev/null 2>&1
}

is_gswarp_active() {
  if [ -f "$STATE_DIR/gswarp-gs.pid" ]; then
    pid="$(cat "$STATE_DIR/gswarp-gs.pid" 2>/dev/null || true)"
    if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
      return 0
    fi
  fi
  if [ -f "/tmp/gswarp-gs.pid" ]; then
    pid="$(cat "/tmp/gswarp-gs.pid" 2>/dev/null || true)"
    if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
      return 0
    fi
  fi
  return 1
}

is_ovpn_active() {
  if [ -f "$STATE_DIR/ovpn.pid" ]; then
    pid="$(cat "$STATE_DIR/ovpn.pid" 2>/dev/null || true)"
    if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
      return 0
    fi
  fi
  ip link show dev tun_ovpn >/dev/null 2>&1
}

is_gsocket_active() {
  if [ -f "$STATE_DIR/gsocket-port.pid" ]; then
    pid="$(cat "$STATE_DIR/gsocket-port.pid" 2>/dev/null || true)"
    if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
      return 0
    fi
  fi
  return 1
}

is_wg_active() {
  ip link show dev wg0 >/dev/null 2>&1
}

# Remove an iptables chain from a table and all references from hook chains
flush_and_delete_chain() {
  tbl="$1"
  chain="$2"
  shift 2
  for hook in "$@"; do
    while iptables -t "$tbl" -D "$hook" -j "$chain" 2>/dev/null; do :; done
  done
  iptables -t "$tbl" -F "$chain" 2>/dev/null || true
  iptables -t "$tbl" -X "$chain" 2>/dev/null || true
}

flush_and_delete_chain6() {
  command -v ip6tables >/dev/null 2>&1 || return 0
  tbl="$1"
  chain="$2"
  shift 2
  for hook in "$@"; do
    while ip6tables -t "$tbl" -D "$hook" -j "$chain" 2>/dev/null; do :; done
  done
  ip6tables -t "$tbl" -F "$chain" 2>/dev/null || true
  ip6tables -t "$tbl" -X "$chain" 2>/dev/null || true
}

# Synchronize /etc/resolv.conf and IPv6 DNS leak protection with active tunnels
sync_dns_resolv() {
  flush_and_delete_chain6 filter BP6_DNS_OUT OUTPUT
  flush_and_delete_chain6 filter BP6_DNS_FWD FORWARD

  active_dns=""
  need_v6_out_block=0

  if is_tor_active && [ "$TOR_NATIVE" = "1" ] && grep -q 'Bootstrapped 100%' "$STATE_DIR/tor.log" 2>/dev/null; then
    active_dns="127.0.0.1"
    need_v6_out_block=1
  elif is_gswarp_active && [ "$GSWARP_NATIVE" = "1" ] && ip -4 addr show dev tun_gswarp 2>/dev/null | grep -q 'inet '; then
    active_dns="$(cat "$STATE_DIR/gswarp.dns" 2>/dev/null || true)"
    [ -z "$active_dns" ] && active_dns="1.1.1.1"
    need_v6_out_block=1
  elif is_ovpn_active && [ "$OVPN_NATIVE" = "1" ] && ip -4 addr show dev tun_ovpn 2>/dev/null | grep -q 'inet '; then
    active_dns="$(cat "$STATE_DIR/ovpn.dns" 2>/dev/null || true)"
    [ -z "$active_dns" ] && active_dns="1.1.1.1"
    need_v6_out_block=1
  elif is_wg_active && [ "$WG_NATIVE" = "1" ] && ip -4 addr show dev wg0 2>/dev/null | grep -q 'inet '; then
    active_dns="${WG_DNS:-1.1.1.1}"
    need_v6_out_block=1
  fi

  if [ "$need_v6_out_block" = "1" ] && command -v ip6tables >/dev/null 2>&1; then
    ip6tables -t filter -N BP6_DNS_OUT 2>/dev/null || true
    ip6tables -t filter -F BP6_DNS_OUT
    ip6tables -t filter -A BP6_DNS_OUT -p udp --dport 53 -j REJECT 2>/dev/null || \
      ip6tables -t filter -A BP6_DNS_OUT -p udp --dport 53 -j DROP 2>/dev/null || true
    ip6tables -t filter -A BP6_DNS_OUT -p tcp --dport 53 -j REJECT 2>/dev/null || \
      ip6tables -t filter -A BP6_DNS_OUT -p tcp --dport 53 -j DROP 2>/dev/null || true
    ip6tables -t filter -I OUTPUT 1 -j BP6_DNS_OUT 2>/dev/null || true
  fi

  if (is_tor_active && [ "$TOR_TETHER" = "1" ]) || \
     (is_gswarp_active && [ "$GSWARP_TETHER" = "1" ] && ip -4 addr show dev tun_gswarp 2>/dev/null | grep -q 'inet ') || \
     (is_ovpn_active && [ "$OVPN_TETHER" = "1" ] && ip -4 addr show dev tun_ovpn 2>/dev/null | grep -q 'inet ') || \
     (is_wg_active && [ "$WG_TETHER" = "1" ] && ip -4 addr show dev wg0 2>/dev/null | grep -q 'inet '); then
    if command -v ip6tables >/dev/null 2>&1; then
      ip6tables -t filter -N BP6_DNS_FWD 2>/dev/null || true
      ip6tables -t filter -F BP6_DNS_FWD
      ip6tables -t filter -A BP6_DNS_FWD -p udp --dport 53 -j REJECT 2>/dev/null || \
        ip6tables -t filter -A BP6_DNS_FWD -p udp --dport 53 -j DROP 2>/dev/null || true
      ip6tables -t filter -A BP6_DNS_FWD -p tcp --dport 53 -j REJECT 2>/dev/null || \
        ip6tables -t filter -A BP6_DNS_FWD -p tcp --dport 53 -j DROP 2>/dev/null || true
      ip6tables -t filter -I FORWARD 1 -j BP6_DNS_FWD 2>/dev/null || true
    fi
  fi

  if [ -n "$active_dns" ]; then
    if [ ! -f "$STATE_DIR/resolv.conf.orig" ] && [ -f /etc/resolv.conf ]; then
      cp -f /etc/resolv.conf "$STATE_DIR/resolv.conf.orig" 2>/dev/null || true
    fi
    {
      echo "# Managed by bananarchy-privacy-ctl (tunneled DNS)"
      echo "nameserver $active_dns"
      if [ "$active_dns" != "1.1.1.1" ]; then
        echo "nameserver 1.1.1.1"
      fi
      if [ "$active_dns" != "127.0.0.1" ]; then
        echo "nameserver 127.0.0.1"
      fi
    } > "$STATE_DIR/resolv.conf.new"
    cp -f "$STATE_DIR/resolv.conf.new" /etc/resolv.conf 2>/dev/null || true
  else
    if [ -f "$STATE_DIR/resolv.conf.orig" ]; then
      cp -f "$STATE_DIR/resolv.conf.orig" /etc/resolv.conf 2>/dev/null || true
      rm -f "$STATE_DIR/resolv.conf.orig"
    fi
    if ! grep -q '^nameserver ' /etc/resolv.conf 2>/dev/null; then
      {
        echo "nameserver 127.0.0.1"
        echo "nameserver 1.1.1.1"
      } > /etc/resolv.conf 2>/dev/null || true
    fi
  fi
}

# Clean or install base policy-routing rules for VPN tunnels
sync_base_vpn_rules() {
  while ip rule del prio 85 2>/dev/null; do :; done
  while ip rule del prio 86 2>/dev/null; do :; done
  while ip rule del prio 90 2>/dev/null; do :; done
  flush_and_delete_chain mangle BP_BYPASS_OUT OUTPUT

  if is_gswarp_active || is_ovpn_active || is_wg_active; then
    ensure_netfilter_modules
    ovpn_gid="$(get_openvpn_gid)"
    iptables -t mangle -N BP_BYPASS_OUT 2>/dev/null || true
    iptables -t mangle -F BP_BYPASS_OUT
    if [ -n "$ovpn_gid" ]; then
      iptables -t mangle -A BP_BYPASS_OUT -m owner --gid-owner "$ovpn_gid" -j MARK --set-mark 0x191 2>/dev/null || true
    fi
    iptables -t mangle -I OUTPUT 1 -j BP_BYPASS_OUT
    ip rule add prio 85 fwmark 0x191 lookup main 2>/dev/null || true
    ip rule add prio 86 fwmark 0xca6c lookup main 2>/dev/null || true
    ip rule add prio 90 lookup main suppress_prefixlength 0 2>/dev/null || true
  fi
}

# Add local/private network exemptions to a NAT chain
add_private_exemptions() {
  chain="$1"
  for net in \
    127.0.0.0/8 \
    10.0.0.0/8 \
    172.16.0.0/12 \
    192.168.0.0/16 \
    100.64.0.0/10 \
    169.254.0.0/16 \
    224.0.0.0/4 \
    255.255.255.255/32; do
    iptables -t nat -A "$chain" -d "$net" -j RETURN
  done
}

# ==============================================================================
# 1. TOR SERVICE & ROUTING
# ==============================================================================
clear_tor_routing() {
  flush_and_delete_chain nat BP_TOR_OUT OUTPUT
  flush_and_delete_chain nat BP_TOR_PRE PREROUTING
  flush_and_delete_chain filter BP_TOR_IN INPUT
  sync_dns_resolv
}

apply_tor_routing() {
  flush_and_delete_chain nat BP_TOR_OUT OUTPUT
  flush_and_delete_chain nat BP_TOR_PRE PREROUTING
  flush_and_delete_chain filter BP_TOR_IN INPUT
  if ! is_tor_active; then
    sync_dns_resolv
    return 0
  fi
  if ! grep -q 'Bootstrapped 100%' "$STATE_DIR/tor.log" 2>/dev/null; then
    sync_dns_resolv
    return 0
  fi
  if [ "$TOR_NATIVE" != "1" ] && [ "$TOR_TETHER" != "1" ]; then
    sync_dns_resolv
    return 0
  fi

  ensure_netfilter_modules
  tor_uid="$(get_tor_uid)"
  ovpn_gid="$(get_openvpn_gid)"

  if [ "$TOR_NATIVE" = "1" ]; then
    iptables -t nat -N BP_TOR_OUT 2>/dev/null || true
    iptables -t nat -F BP_TOR_OUT
    if [ -n "$tor_uid" ]; then
      iptables -t nat -A BP_TOR_OUT -m owner --uid-owner "$tor_uid" -j RETURN
    fi
    if [ -n "$ovpn_gid" ]; then
      iptables -t nat -A BP_TOR_OUT -m owner --gid-owner "$ovpn_gid" -j RETURN
    fi
    # Redirect UDP DNS (including queries to 127.0.0.1:53) to Tor DNSPort 9053 before -o lo RETURN
    iptables -t nat -A BP_TOR_OUT -p udp --dport 53 -j REDIRECT --to-ports 9053
    iptables -t nat -A BP_TOR_OUT -d 10.192.0.0/10 -p tcp -m tcp --syn -j REDIRECT --to-ports 9040
    iptables -t nat -A BP_TOR_OUT -o lo -j RETURN
    # Tunnel TCP DNS (port 53) to external servers via TransPort 9040 (Tor DNSPort is UDP-only)
    iptables -t nat -A BP_TOR_OUT -p tcp -m tcp --syn --dport 53 -j REDIRECT --to-ports 9040
    add_private_exemptions BP_TOR_OUT
    iptables -t nat -A BP_TOR_OUT -p tcp -m tcp --syn -j REDIRECT --to-ports 9040
    iptables -t nat -I OUTPUT 1 -j BP_TOR_OUT
  fi

  if [ "$TOR_TETHER" = "1" ]; then
    sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true
    iptables -t nat -N BP_TOR_PRE 2>/dev/null || true
    iptables -t nat -F BP_TOR_PRE
    # Never redirect SSH to the phone itself over USB or hotspot
    iptables -t nat -A BP_TOR_PRE -p tcp --dport 22 -j RETURN
    iptables -t nat -A BP_TOR_PRE -i usb0 -d 10.192.0.0/10 -p tcp -m tcp --syn -j REDIRECT --to-ports 9040
    iptables -t nat -A BP_TOR_PRE -s 10.42.0.0/24 -d 10.192.0.0/10 -p tcp -m tcp --syn -j REDIRECT --to-ports 9040
    iptables -t nat -A BP_TOR_PRE -i usb0 -p udp --dport 53 -j REDIRECT --to-ports 9053
    iptables -t nat -A BP_TOR_PRE -i usb0 -p tcp -m tcp --syn --dport 53 -j REDIRECT --to-ports 9040
    iptables -t nat -A BP_TOR_PRE -s 10.42.0.0/24 -p udp --dport 53 -j REDIRECT --to-ports 9053
    iptables -t nat -A BP_TOR_PRE -s 10.42.0.0/24 -p tcp -m tcp --syn --dport 53 -j REDIRECT --to-ports 9040
    add_private_exemptions BP_TOR_PRE
    iptables -t nat -A BP_TOR_PRE -i usb0 -p tcp -m tcp --syn -j REDIRECT --to-ports 9040
    iptables -t nat -A BP_TOR_PRE -s 10.42.0.0/24 -p tcp -m tcp --syn -j REDIRECT --to-ports 9040
    iptables -t nat -I PREROUTING 1 -j BP_TOR_PRE

    iptables -t filter -N BP_TOR_IN 2>/dev/null || true
    iptables -t filter -F BP_TOR_IN
    iptables -t filter -A BP_TOR_IN -i usb0 -p tcp --dport 9040 -j ACCEPT
    iptables -t filter -A BP_TOR_IN -i usb0 -p udp --dport 9053 -j ACCEPT
    iptables -t filter -A BP_TOR_IN -s 10.42.0.0/24 -p tcp --dport 9040 -j ACCEPT
    iptables -t filter -A BP_TOR_IN -s 10.42.0.0/24 -p udp --dport 9053 -j ACCEPT
    iptables -t filter -I INPUT 1 -j BP_TOR_IN
  fi

  sync_dns_resolv
}

start_tor() {
  if is_tor_active; then
    apply_tor_routing
    return 0
  fi
  tor_uid="$(get_tor_uid)"
  tor_gid="$(awk -F: '/^tor:/ {print $4; exit}' /etc/passwd 2>/dev/null || echo "114")"
  mkdir -p /var/lib/tor "$STATE_DIR"
  chmod 0755 "$STATE_DIR" 2>/dev/null || true
  chown -R "${tor_uid:-109}:${tor_gid:-114}" /var/lib/tor 2>/dev/null || true
  chmod 0700 /var/lib/tor 2>/dev/null || true

  cat > "$STATE_DIR/torrc" <<EOF
User tor
DataDirectory /var/lib/tor
PidFile $STATE_DIR/tor.pid
RunAsDaemon 1
AvoidDiskWrites 1
GeoIPFile /dev/null
GeoIPv6File /dev/null
SocksPort 127.0.0.1:9050
TransPort 0.0.0.0:9040
DNSPort 0.0.0.0:9053
VirtualAddrNetworkIPv4 10.192.0.0/10
AutomapHostsOnResolve 1
Log notice file $STATE_DIR/tor.log
EOF
  : > "$STATE_DIR/tor.log"
  : > "$STATE_DIR/tor.pid"
  chown "${tor_uid:-109}:${tor_gid:-114}" "$STATE_DIR/tor.log" "$STATE_DIR/tor.pid" "$STATE_DIR/torrc" 2>/dev/null || true
  chmod 0644 "$STATE_DIR/tor.log" "$STATE_DIR/tor.pid" "$STATE_DIR/torrc" 2>/dev/null || true
  /usr/bin/tor -f "$STATE_DIR/torrc" >/dev/null 2>&1
  # Wait up to 4 seconds for cached Tor bootstrap; if still bootstrapping, finish asynchronously
  i=0
  while [ "$i" -lt 20 ]; do
    if grep -q 'Bootstrapped 100%' "$STATE_DIR/tor.log" 2>/dev/null; then
      break
    fi
    sleep 0.2
    i="$((i + 1))"
  done
  if grep -q 'Bootstrapped 100%' "$STATE_DIR/tor.log" 2>/dev/null; then
    apply_tor_routing
  else
    sync_dns_resolv
    (
      j=0
      while [ "$j" -lt 120 ]; do
        if ! is_tor_active; then
          exit 0
        fi
        if grep -q 'Bootstrapped 100%' "$STATE_DIR/tor.log" 2>/dev/null; then
          /usr/bin/bananarchy-privacy-ctl _tor_up >/dev/null 2>&1
          exit 0
        fi
        sleep 0.5
        j="$((j + 1))"
      done
    ) >/dev/null 2>&1 </dev/null &
  fi
}

stop_tor() {
  clear_tor_routing
  if [ -f "$STATE_DIR/tor.pid" ]; then
    kill "$(cat "$STATE_DIR/tor.pid" 2>/dev/null)" 2>/dev/null || true
    rm -f "$STATE_DIR/tor.pid"
  fi
  pkill -x tor 2>/dev/null || true
  sync_dns_resolv
}

# ==============================================================================
# SHARED VPN TUNNEL ROUTING HELPER (GS-Warp, OpenVPN, WireGuard)
# ==============================================================================
clear_vpn_routing() {
  dev="$1"
  table="$2"
  prio_base="$3"
  tag="$4"

  for p in "$prio_base" "$((prio_base + 1))" "$((prio_base + 2))" "$((prio_base + 3))"; do
    while ip rule del prio "$p" 2>/dev/null; do :; done
  done
  ip route flush table "$table" 2>/dev/null || true
  flush_and_delete_chain nat "BP_${tag}_POST" POSTROUTING
  flush_and_delete_chain filter "BP_${tag}_FWD" FORWARD
  flush_and_delete_chain nat "BP_${tag}_DNS_O" OUTPUT
  flush_and_delete_chain nat "BP_${tag}_DNS_P" PREROUTING
  sync_base_vpn_rules
  sync_dns_resolv
}

apply_vpn_routing() {
  dev="$1"
  table="$2"
  prio_base="$3"
  tag="$4"
  native="$5"
  tether="$6"
  dns_ip="${7:-1.1.1.1}"

  for p in "$prio_base" "$((prio_base + 1))" "$((prio_base + 2))" "$((prio_base + 3))"; do
    while ip rule del prio "$p" 2>/dev/null; do :; done
  done
  ip route flush table "$table" 2>/dev/null || true
  flush_and_delete_chain nat "BP_${tag}_POST" POSTROUTING
  flush_and_delete_chain filter "BP_${tag}_FWD" FORWARD
  flush_and_delete_chain nat "BP_${tag}_DNS_O" OUTPUT
  flush_and_delete_chain nat "BP_${tag}_DNS_P" PREROUTING

  # Only activate tunnel default routes and DNS redirection once the tunnel has an IPv4 address
  if ! ip -4 addr show dev "$dev" 2>/dev/null | grep -q 'inet '; then
    sync_base_vpn_rules
    sync_dns_resolv
    return 0
  fi

  sync_base_vpn_rules
  ip route replace default dev "$dev" table "$table" 2>/dev/null || true
  ovpn_gid="$(get_openvpn_gid)"
  tor_uid="$(get_tor_uid)"

  if [ "$native" = "1" ]; then
    ip rule add prio "$prio_base" iif lo lookup "$table" 2>/dev/null || true
    if [ -n "$dns_ip" ]; then
      iptables -t nat -N "BP_${tag}_DNS_O" 2>/dev/null || true
      iptables -t nat -F "BP_${tag}_DNS_O"
      if [ -n "$ovpn_gid" ]; then
        iptables -t nat -A "BP_${tag}_DNS_O" -m owner --gid-owner "$ovpn_gid" -j RETURN
      fi
      if [ -n "$tor_uid" ]; then
        iptables -t nat -A "BP_${tag}_DNS_O" -m owner --uid-owner "$tor_uid" -j RETURN
      fi
      # Allow local queries to 127.0.0.1:53 (dnsmasq) so saddr=127.0.0.1 is never DNATed off-loopback
      iptables -t nat -A "BP_${tag}_DNS_O" -d 127.0.0.0/8 -j RETURN
      iptables -t nat -A "BP_${tag}_DNS_O" -p udp --dport 53 -j DNAT --to-destination "${dns_ip}:53"
      iptables -t nat -A "BP_${tag}_DNS_O" -p tcp --dport 53 -j DNAT --to-destination "${dns_ip}:53"
      iptables -t nat -I OUTPUT 1 -j "BP_${tag}_DNS_O"
    fi
  fi

  if [ "$tether" = "1" ]; then
    sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true
    ip rule add prio "$((prio_base + 1))" iif usb0 lookup "$table" 2>/dev/null || true
    ip rule add prio "$((prio_base + 2))" from 10.42.0.0/24 lookup "$table" 2>/dev/null || true
    ip rule add prio "$((prio_base + 3))" from 172.16.0.0/16 lookup "$table" 2>/dev/null || true

    iptables -t nat -N "BP_${tag}_POST" 2>/dev/null || true
    iptables -t nat -F "BP_${tag}_POST"
    iptables -t nat -A "BP_${tag}_POST" -o "$dev" -j MASQUERADE
    iptables -t nat -I POSTROUTING 1 -j "BP_${tag}_POST"

    iptables -t filter -N "BP_${tag}_FWD" 2>/dev/null || true
    iptables -t filter -F "BP_${tag}_FWD"
    iptables -t filter -A "BP_${tag}_FWD" -o "$dev" -j ACCEPT
    iptables -t filter -A "BP_${tag}_FWD" -i "$dev" -j ACCEPT
    iptables -t filter -I FORWARD 1 -j "BP_${tag}_FWD"

    if [ -n "$dns_ip" ]; then
      iptables -t nat -N "BP_${tag}_DNS_P" 2>/dev/null || true
      iptables -t nat -F "BP_${tag}_DNS_P"
      iptables -t nat -A "BP_${tag}_DNS_P" -i usb0 -p udp --dport 53 -j DNAT --to-destination "${dns_ip}:53"
      iptables -t nat -A "BP_${tag}_DNS_P" -i usb0 -p tcp --dport 53 -j DNAT --to-destination "${dns_ip}:53"
      iptables -t nat -A "BP_${tag}_DNS_P" -s 10.42.0.0/24 -p udp --dport 53 -j DNAT --to-destination "${dns_ip}:53"
      iptables -t nat -A "BP_${tag}_DNS_P" -s 10.42.0.0/24 -p tcp --dport 53 -j DNAT --to-destination "${dns_ip}:53"
      iptables -t nat -I PREROUTING 1 -j "BP_${tag}_DNS_P"
    fi
  fi

  # Always allow outbound NAT when Native traffic exits the VPN interface
  if [ "$native" = "1" ] && [ "$tether" != "1" ]; then
    iptables -t nat -N "BP_${tag}_POST" 2>/dev/null || true
    iptables -t nat -F "BP_${tag}_POST"
    iptables -t nat -A "BP_${tag}_POST" -o "$dev" -j MASQUERADE
    iptables -t nat -I POSTROUTING 1 -j "BP_${tag}_POST"
  fi

  sync_dns_resolv
}

# ==============================================================================
# 2. GS-WARP SERVICE & ROUTING (tun_gswarp, table 210, prio 110)
# ==============================================================================
apply_gswarp_routing() {
  gsw_dns="$(cat "$STATE_DIR/gswarp.dns" 2>/dev/null || true)"
  [ -z "$gsw_dns" ] && gsw_dns="1.1.1.1"
  apply_vpn_routing "tun_gswarp" 210 110 "GSW" "$GSWARP_NATIVE" "$GSWARP_TETHER" "$gsw_dns"
}

start_gswarp() {
  stop_gswarp
  if [ ! -f "$GSWARP_OVPN" ]; then
    echo "Error: GS-Warp config '$GSWARP_OVPN' not found." >&2
    return 1
  fi
  if [ -z "$GSWARP_SECRET" ]; then
    GSWARP_SECRET="$(md5sum "$GSWARP_OVPN" | awk '{print $1}')"
  fi
  ensure_netfilter_modules

  start-stop-daemon -S -g openvpn -x /usr/bin/gs-netcat -- \
    -D -p 1194 -s "$GSWARP_SECRET" 2>/dev/null || \
    /usr/bin/gs-netcat -D -p 1194 -s "$GSWARP_SECRET" 2>/dev/null
  sleep 0.2
  gs_pid="$(pgrep -f "gs-netcat -D -p 1194" | head -n 1 || true)"
  if [ -z "$gs_pid" ]; then
    echo "Error: failed to start gs-netcat for GS-Warp." >&2
    return 1
  fi
  echo "$gs_pid" > "$STATE_DIR/gswarp-gs.pid"
  echo "$gs_pid" > "/tmp/gswarp-gs.pid"

  cat > "$STATE_DIR/gswarp-up.sh" <<'EOF'
#!/bin/sh
pushed_dns="$(env | sed -n 's/^foreign_option_[0-9]*=dhcp-option DNS \([0-9.]*\).*/\1/p' | head -n 1)"
if [ -n "$pushed_dns" ]; then
  echo "$pushed_dns" > /tmp/bananarchy-privacy/gswarp.dns
fi
/usr/bin/bananarchy-privacy-ctl _ovpn_up gswarp >/dev/null 2>&1 &
exit 0
EOF
  chmod 0755 "$STATE_DIR/gswarp-up.sh"

  start-stop-daemon -S -g openvpn -x /usr/sbin/openvpn -- \
    --daemon gs-warp \
    --config "$GSWARP_OVPN" \
    --dev tun_gswarp \
    --mark 401 \
    --route-noexec \
    --script-security 2 \
    --up "$STATE_DIR/gswarp-up.sh" \
    --writepid "$STATE_DIR/gswarp-ov.pid" >/dev/null 2>&1 || true

  sleep 0.2
  if [ -f "$STATE_DIR/gswarp-ov.pid" ]; then
    cp -f "$STATE_DIR/gswarp-ov.pid" /tmp/gswarp-ov.pid 2>/dev/null || true
  fi
  sync_base_vpn_rules
  sync_dns_resolv
}

stop_gswarp() {
  rm -f "$STATE_DIR/gswarp.dns"
  clear_vpn_routing "tun_gswarp" 210 110 "GSW"
  for pidf in "$STATE_DIR/gswarp-ov.pid" "/tmp/gswarp-ov.pid" "$STATE_DIR/gswarp-gs.pid" "/tmp/gswarp-gs.pid"; do
    if [ -f "$pidf" ]; then
      kill "$(cat "$pidf" 2>/dev/null)" 2>/dev/null || true
      rm -f "$pidf"
    fi
  done
  pkill -f "gs-netcat -D -p 1194" 2>/dev/null || true
  pkill -f "openvpn.*tun_gswarp" 2>/dev/null || true
  ip link del dev tun_gswarp 2>/dev/null || true
  sync_base_vpn_rules
  sync_dns_resolv
}

# ==============================================================================
# 3. OPENVPN SERVICE & ROUTING (tun_ovpn, table 220, prio 120)
# ==============================================================================
apply_ovpn_routing() {
  ovp_dns="$(cat "$STATE_DIR/ovpn.dns" 2>/dev/null || true)"
  [ -z "$ovp_dns" ] && ovp_dns="1.1.1.1"
  apply_vpn_routing "tun_ovpn" 220 120 "OVP" "$OVPN_NATIVE" "$OVPN_TETHER" "$ovp_dns"
}

start_ovpn() {
  stop_ovpn
  if [ ! -f "$OVPN_CONFIG" ]; then
    echo "Error: OpenVPN config '$OVPN_CONFIG' not found." >&2
    return 1
  fi
  ensure_netfilter_modules

  cat > "$STATE_DIR/ovpn-up.sh" <<'EOF'
#!/bin/sh
pushed_dns="$(env | sed -n 's/^foreign_option_[0-9]*=dhcp-option DNS \([0-9.]*\).*/\1/p' | head -n 1)"
if [ -n "$pushed_dns" ]; then
  echo "$pushed_dns" > /tmp/bananarchy-privacy/ovpn.dns
fi
/usr/bin/bananarchy-privacy-ctl _ovpn_up openvpn >/dev/null 2>&1 &
exit 0
EOF
  chmod 0755 "$STATE_DIR/ovpn-up.sh"

  start-stop-daemon -S -g openvpn -x /usr/sbin/openvpn -- \
    --daemon bananarchy-ovpn \
    --config "$OVPN_CONFIG" \
    --dev tun_ovpn \
    --mark 401 \
    --route-noexec \
    --script-security 2 \
    --up "$STATE_DIR/ovpn-up.sh" \
    --writepid "$STATE_DIR/ovpn.pid" >/dev/null 2>&1 || true

  sleep 0.2
  sync_base_vpn_rules
  sync_dns_resolv
}

stop_ovpn() {
  rm -f "$STATE_DIR/ovpn.dns"
  clear_vpn_routing "tun_ovpn" 220 120 "OVP"
  if [ -f "$STATE_DIR/ovpn.pid" ]; then
    kill "$(cat "$STATE_DIR/ovpn.pid" 2>/dev/null)" 2>/dev/null || true
    rm -f "$STATE_DIR/ovpn.pid"
  fi
  pkill -f "openvpn.*tun_ovpn" 2>/dev/null || true
  ip link del dev tun_ovpn 2>/dev/null || true
  sync_base_vpn_rules
  sync_dns_resolv
}

# ==============================================================================
# 4. GSOCKET SINGLE TCP PORT SERVICE & ROUTING
# ==============================================================================
clear_gsocket_routing() {
  flush_and_delete_chain nat BP_GS_OUT OUTPUT
  flush_and_delete_chain nat BP_GS_PRE PREROUTING
  flush_and_delete_chain filter BP_GS_IN INPUT
  sync_dns_resolv
}

apply_gsocket_routing() {
  clear_gsocket_routing
  if ! is_gsocket_active; then
    return 0
  fi
  if [ "$GSOCKET_MODE" = "server" ]; then
    return 0
  fi
  if [ "$GSOCKET_NATIVE" != "1" ] && [ "$GSOCKET_TETHER" != "1" ]; then
    return 0
  fi
  case "$GSOCKET_PORT" in
    ''|*[!0-9]*) return 0 ;;
  esac

  ensure_netfilter_modules
  ovpn_gid="$(get_openvpn_gid)"

  if [ "$GSOCKET_NATIVE" = "1" ]; then
    iptables -t nat -N BP_GS_OUT 2>/dev/null || true
    iptables -t nat -F BP_GS_OUT
    if [ -n "$ovpn_gid" ]; then
      iptables -t nat -A BP_GS_OUT -m owner --gid-owner "$ovpn_gid" -j RETURN
    fi
    if [ "$GSOCKET_PORT" != "53" ]; then
      iptables -t nat -A BP_GS_OUT -d 127.0.0.0/8 -j RETURN
    fi
    iptables -t nat -A BP_GS_OUT -d 172.16.42.0/24 -j RETURN
    iptables -t nat -A BP_GS_OUT -p tcp --dport "$GSOCKET_PORT" -j REDIRECT --to-ports "$GSOCKET_PORT"
    iptables -t nat -I OUTPUT 1 -j BP_GS_OUT
  fi

  if [ "$GSOCKET_TETHER" = "1" ]; then
    sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true
    iptables -t nat -N BP_GS_PRE 2>/dev/null || true
    iptables -t nat -F BP_GS_PRE
    if [ "$GSOCKET_PORT" = "22" ]; then
      iptables -t nat -A BP_GS_PRE -d 172.16.42.1/32 -p tcp --dport 22 -j RETURN
      iptables -t nat -A BP_GS_PRE -d 10.42.0.1/32 -p tcp --dport 22 -j RETURN
    fi
    iptables -t nat -A BP_GS_PRE -i usb0 -p tcp --dport "$GSOCKET_PORT" -j REDIRECT --to-ports "$GSOCKET_PORT"
    iptables -t nat -A BP_GS_PRE -s 10.42.0.0/24 -p tcp --dport "$GSOCKET_PORT" -j REDIRECT --to-ports "$GSOCKET_PORT"
    iptables -t nat -I PREROUTING 1 -j BP_GS_PRE

    iptables -t filter -N BP_GS_IN 2>/dev/null || true
    iptables -t filter -F BP_GS_IN
    iptables -t filter -A BP_GS_IN -i usb0 -p tcp --dport "$GSOCKET_PORT" -j ACCEPT
    iptables -t filter -A BP_GS_IN -s 10.42.0.0/24 -p tcp --dport "$GSOCKET_PORT" -j ACCEPT
    iptables -t filter -I INPUT 1 -j BP_GS_IN
  fi
}

start_gsocket() {
  stop_gsocket
  if [ -z "$GSOCKET_SECRET" ]; then
    echo "Error: GSocket secret is empty." >&2
    return 1
  fi
  case "$GSOCKET_PORT" in
    ''|*[!0-9]*)
      echo "Error: invalid TCP port '$GSOCKET_PORT'." >&2
      return 1
      ;;
  esac

  if [ "$GSOCKET_MODE" = "server" ]; then
    start-stop-daemon -S -g openvpn -x /usr/bin/gs-netcat -- \
      -D -l -s "$GSOCKET_SECRET" -d 127.0.0.1 -p "$GSOCKET_PORT" 2>/dev/null || \
      /usr/bin/gs-netcat -D -l -s "$GSOCKET_SECRET" -d 127.0.0.1 -p "$GSOCKET_PORT" 2>/dev/null
    sleep 0.2
    gs_pid="$(pgrep -f "gs-netcat -D -l -s .* -p $GSOCKET_PORT" | head -n 1 || true)"
  else
    start-stop-daemon -S -g openvpn -x /usr/bin/gs-netcat -- \
      -D -s "$GSOCKET_SECRET" -p "$GSOCKET_PORT" 2>/dev/null || \
      /usr/bin/gs-netcat -D -s "$GSOCKET_SECRET" -p "$GSOCKET_PORT" 2>/dev/null
    sleep 0.2
    gs_pid="$(pgrep -f "gs-netcat -D -s .* -p $GSOCKET_PORT" | head -n 1 || true)"
  fi

  if [ -z "$gs_pid" ]; then
    echo "Error: failed to start gs-netcat on port $GSOCKET_PORT." >&2
    return 1
  fi
  echo "$gs_pid" > "$STATE_DIR/gsocket-port.pid"
  apply_gsocket_routing
}

stop_gsocket() {
  clear_gsocket_routing
  if [ -f "$STATE_DIR/gsocket-port.pid" ]; then
    kill "$(cat "$STATE_DIR/gsocket-port.pid" 2>/dev/null)" 2>/dev/null || true
    rm -f "$STATE_DIR/gsocket-port.pid"
  fi
  pkill -f "gs-netcat -D -s .* -p $GSOCKET_PORT" 2>/dev/null || true
  pkill -f "gs-netcat -D -l -s .* -p $GSOCKET_PORT" 2>/dev/null || true
}

# ==============================================================================
# 5. WIREGUARD SERVICE & ROUTING (wg0, table 230, prio 130)
# ==============================================================================
apply_wg_routing() {
  apply_vpn_routing "wg0" 230 130 "WG" "$WG_NATIVE" "$WG_TETHER" "${WG_DNS:-1.1.1.1}"
}

start_wg() {
  stop_wg
  if [ -z "$WG_PRIVKEY" ] || [ -z "$WG_PEER_PUBKEY" ]; then
    echo "Error: WireGuard PrivateKey and Peer PublicKey are required." >&2
    return 1
  fi
  ensure_netfilter_modules

  ip link add dev wg0 type wireguard 2>/dev/null || return 1
  printf "%s\n" "$WG_PRIVKEY" > "$STATE_DIR/wg.key"
  chmod 0600 "$STATE_DIR/wg.key"

  if [ -n "$WG_PSK" ]; then
    printf "%s\n" "$WG_PSK" > "$STATE_DIR/wg.psk"
    chmod 0600 "$STATE_DIR/wg.psk"
    if [ -n "$WG_ENDPOINT" ]; then
      wg set wg0 fwmark 0xca6c private-key "$STATE_DIR/wg.key" \
        peer "$WG_PEER_PUBKEY" preshared-key "$STATE_DIR/wg.psk" \
        endpoint "$WG_ENDPOINT" allowed-ips 0.0.0.0/0 persistent-keepalive 25
    else
      wg set wg0 fwmark 0xca6c private-key "$STATE_DIR/wg.key" \
        peer "$WG_PEER_PUBKEY" preshared-key "$STATE_DIR/wg.psk" \
        allowed-ips 0.0.0.0/0 persistent-keepalive 25
    fi
  else
    if [ -n "$WG_ENDPOINT" ]; then
      wg set wg0 fwmark 0xca6c private-key "$STATE_DIR/wg.key" \
        peer "$WG_PEER_PUBKEY" endpoint "$WG_ENDPOINT" \
        allowed-ips 0.0.0.0/0 persistent-keepalive 25
    else
      wg set wg0 fwmark 0xca6c private-key "$STATE_DIR/wg.key" \
        peer "$WG_PEER_PUBKEY" allowed-ips 0.0.0.0/0 persistent-keepalive 25
    fi
  fi
  rm -f "$STATE_DIR/wg.key" "$STATE_DIR/wg.psk"

  for addr in $(printf "%s" "$WG_ADDRESS" | tr ',' ' '); do
    ip addr add "$addr" dev wg0 2>/dev/null || true
  done
  ip link set mtu 1420 up dev wg0
  apply_wg_routing
}

stop_wg() {
  clear_vpn_routing "wg0" 230 130 "WG"
  ip link del dev wg0 2>/dev/null || true
  sync_base_vpn_rules
}

# ==============================================================================
# STATUS & COMMAND DISPATCH
# ==============================================================================
print_status() {
  if is_tor_active; then
    echo "TOR_ACTIVE=1"
    boot="$(grep -o 'Bootstrapped [0-9]*%' "$STATE_DIR/tor.log" 2>/dev/null | tail -n 1 | awk '{print $2}' || true)"
    echo "TOR_BOOTSTRAPPED=${boot:-0%}"
  else
    echo "TOR_ACTIVE=0"
    echo "TOR_BOOTSTRAPPED=Off"
  fi
  echo "TOR_NATIVE=$TOR_NATIVE"
  echo "TOR_TETHER=$TOR_TETHER"

  if is_gswarp_active; then
    echo "GSWARP_ACTIVE=1"
    tun_ip="$(ip -4 -o addr show dev tun_gswarp 2>/dev/null | awk '{print $4}' | head -n 1 || true)"
    echo "GSWARP_TUN_IP=${tun_ip:-Connecting...}"
  else
    echo "GSWARP_ACTIVE=0"
    echo "GSWARP_TUN_IP=Off"
  fi
  echo "GSWARP_NATIVE=$GSWARP_NATIVE"
  echo "GSWARP_TETHER=$GSWARP_TETHER"
  echo "GSWARP_SECRET=$GSWARP_SECRET"
  echo "GSWARP_OVPN=$GSWARP_OVPN"

  if is_ovpn_active; then
    echo "OVPN_ACTIVE=1"
    tun_ip="$(ip -4 -o addr show dev tun_ovpn 2>/dev/null | awk '{print $4}' | head -n 1 || true)"
    echo "OVPN_TUN_IP=${tun_ip:-Connecting...}"
  else
    echo "OVPN_ACTIVE=0"
    echo "OVPN_TUN_IP=Off"
  fi
  echo "OVPN_NATIVE=$OVPN_NATIVE"
  echo "OVPN_TETHER=$OVPN_TETHER"
  echo "OVPN_CONFIG=$OVPN_CONFIG"

  if is_gsocket_active; then
    echo "GSOCKET_ACTIVE=1"
  else
    echo "GSOCKET_ACTIVE=0"
  fi
  echo "GSOCKET_NATIVE=$GSOCKET_NATIVE"
  echo "GSOCKET_TETHER=$GSOCKET_TETHER"
  echo "GSOCKET_SECRET=$GSOCKET_SECRET"
  echo "GSOCKET_PORT=$GSOCKET_PORT"
  echo "GSOCKET_MODE=$GSOCKET_MODE"

  if is_wg_active; then
    echo "WG_ACTIVE=1"
    tun_ip="$(ip -4 -o addr show dev wg0 2>/dev/null | awk '{print $4}' | head -n 1 || true)"
    echo "WG_TUN_IP=${tun_ip:-Up}"
  else
    echo "WG_ACTIVE=0"
    echo "WG_TUN_IP=Off"
  fi
  echo "WG_NATIVE=$WG_NATIVE"
  echo "WG_TETHER=$WG_TETHER"
  echo "WG_PRIVKEY=$WG_PRIVKEY"
  echo "WG_PUBKEY=$WG_PUBKEY"
  echo "WG_PEER_PUBKEY=$WG_PEER_PUBKEY"
  echo "WG_PSK=$WG_PSK"
  echo "WG_ENDPOINT=$WG_ENDPOINT"
  echo "WG_ADDRESS=$WG_ADDRESS"
  echo "WG_DNS=$WG_DNS"

  if ip -4 addr show dev wlan0 2>/dev/null | grep -q '10\.42\.0\.1'; then
    echo "HOTSPOT_ACTIVE=1"
  else
    echo "HOTSPOT_ACTIVE=0"
  fi
  if ip link show dev usb0 2>/dev/null | grep -q 'UP'; then
    echo "USBTETHER_ACTIVE=1"
  else
    echo "USBTETHER_ACTIVE=0"
  fi
}

load_conf

case "$CMD" in
  status)
    print_status
    ;;
  _tor_up)
    apply_tor_routing
    ;;
  _ovpn_up)
    svc="${2:-}"
    if [ "$svc" = "gswarp" ]; then
      apply_gswarp_routing
    elif [ "$svc" = "openvpn" ]; then
      apply_ovpn_routing
    fi
    ;;
  tor)
    sub="${2:-status}"
    case "$sub" in
      start) start_tor ;;
      stop) stop_tor ;;
      toggle)
        if is_tor_active; then stop_tor; else start_tor; fi
        ;;
      route)
        TOR_NATIVE="${3:-0}"
        TOR_TETHER="${4:-0}"
        save_conf
        apply_tor_routing
        ;;
    esac
    ;;
  gswarp)
    sub="${2:-status}"
    case "$sub" in
      start) start_gswarp ;;
      stop) stop_gswarp ;;
      toggle)
        if is_gswarp_active; then stop_gswarp; else start_gswarp; fi
        ;;
      route)
        GSWARP_NATIVE="${3:-0}"
        GSWARP_TETHER="${4:-0}"
        save_conf
        apply_gswarp_routing
        ;;
      config)
        GSWARP_SECRET="${3:-$GSWARP_SECRET}"
        if [ -n "${4:-}" ]; then
          GSWARP_OVPN="$4"
        fi
        save_conf
        if is_gswarp_active; then
          start_gswarp
        fi
        ;;
      reset-secret)
        if [ -f "$GSWARP_OVPN" ]; then
          GSWARP_SECRET="$(md5sum "$GSWARP_OVPN" | awk '{print $1}')"
          save_conf
        fi
        ;;
    esac
    ;;
  openvpn)
    sub="${2:-status}"
    case "$sub" in
      start) start_ovpn ;;
      stop) stop_ovpn ;;
      toggle)
        if is_ovpn_active; then stop_ovpn; else start_ovpn; fi
        ;;
      route)
        OVPN_NATIVE="${3:-0}"
        OVPN_TETHER="${4:-0}"
        save_conf
        apply_ovpn_routing
        ;;
      config)
        if [ -n "${3:-}" ]; then
          OVPN_CONFIG="$3"
          save_conf
          if is_ovpn_active; then
            start_ovpn
          fi
        fi
        ;;
    esac
    ;;
  gsocket)
    sub="${2:-status}"
    case "$sub" in
      start) start_gsocket ;;
      stop) stop_gsocket ;;
      toggle)
        if is_gsocket_active; then stop_gsocket; else start_gsocket; fi
        ;;
      route)
        GSOCKET_NATIVE="${3:-0}"
        GSOCKET_TETHER="${4:-0}"
        save_conf
        apply_gsocket_routing
        ;;
      config)
        GSOCKET_SECRET="${3:-$GSOCKET_SECRET}"
        GSOCKET_PORT="${4:-$GSOCKET_PORT}"
        GSOCKET_MODE="${5:-$GSOCKET_MODE}"
        save_conf
        if is_gsocket_active; then
          start_gsocket
        fi
        ;;
      gensecret)
        new_sec="$(/usr/bin/gs-netcat -g 2>/dev/null | head -n 1 | tr -d '\r\n')"
        if [ -n "$new_sec" ]; then
          GSOCKET_SECRET="$new_sec"
          save_conf
        fi
        ;;
    esac
    ;;
  wireguard)
    sub="${2:-status}"
    case "$sub" in
      start) start_wg ;;
      stop) stop_wg ;;
      toggle)
        if is_wg_active; then stop_wg; else start_wg; fi
        ;;
      route)
        WG_NATIVE="${3:-0}"
        WG_TETHER="${4:-0}"
        save_conf
        apply_wg_routing
        ;;
      config)
        WG_PRIVKEY="${3:-$WG_PRIVKEY}"
        WG_PEER_PUBKEY="${4:-$WG_PEER_PUBKEY}"
        WG_PSK="${5:-}"
        WG_ENDPOINT="${6:-$WG_ENDPOINT}"
        WG_ADDRESS="${7:-$WG_ADDRESS}"
        WG_DNS="${8:-$WG_DNS}"
        if [ -n "$WG_PRIVKEY" ] && command -v wg >/dev/null 2>&1; then
          WG_PUBKEY="$(printf "%s\n" "$WG_PRIVKEY" | wg pubkey 2>/dev/null || true)"
        fi
        save_conf
        if is_wg_active; then
          start_wg
        fi
        ;;
      genkey)
        if command -v wg >/dev/null 2>&1; then
          WG_PRIVKEY="$(wg genkey)"
          WG_PUBKEY="$(printf "%s\n" "$WG_PRIVKEY" | wg pubkey)"
          save_conf
        fi
        ;;
      import)
        conf_path="${3:-}"
        if [ -f "$conf_path" ]; then
          priv="$(awk -F'=' '/^[[:space:]]*PrivateKey[[:space:]]*=/ {sub(/^[[:space:]]*PrivateKey[[:space:]]*=[[:space:]]*/, ""); gsub(/[[:space:]\r]/, ""); print; exit}' "$conf_path")"
          addr="$(awk -F'=' '/^[[:space:]]*Address[[:space:]]*=/ {sub(/^[[:space:]]*Address[[:space:]]*=[[:space:]]*/, ""); gsub(/[[:space:]\r]/, ""); print; exit}' "$conf_path")"
          dns="$(awk -F'=' '/^[[:space:]]*DNS[[:space:]]*=/ {sub(/^[[:space:]]*DNS[[:space:]]*=[[:space:]]*/, ""); gsub(/[[:space:]\r]/, ""); sub(/,.*/, ""); print; exit}' "$conf_path")"
          pub="$(awk -F'=' '/^[[:space:]]*PublicKey[[:space:]]*=/ {sub(/^[[:space:]]*PublicKey[[:space:]]*=[[:space:]]*/, ""); gsub(/[[:space:]\r]/, ""); print; exit}' "$conf_path")"
          psk="$(awk -F'=' '/^[[:space:]]*PresharedKey[[:space:]]*=/ {sub(/^[[:space:]]*PresharedKey[[:space:]]*=[[:space:]]*/, ""); gsub(/[[:space:]\r]/, ""); print; exit}' "$conf_path")"
          endp="$(awk -F'=' '/^[[:space:]]*Endpoint[[:space:]]*=/ {sub(/^[[:space:]]*Endpoint[[:space:]]*=[[:space:]]*/, ""); gsub(/[[:space:]\r]/, ""); print; exit}' "$conf_path")"
          [ -n "$priv" ] && WG_PRIVKEY="$priv"
          [ -n "$addr" ] && WG_ADDRESS="$addr"
          [ -n "$dns" ] && WG_DNS="$dns"
          [ -n "$pub" ] && WG_PEER_PUBKEY="$pub"
          WG_PSK="$psk"
          [ -n "$endp" ] && WG_ENDPOINT="$endp"
          if [ -n "$WG_PRIVKEY" ] && command -v wg >/dev/null 2>&1; then
            WG_PUBKEY="$(printf "%s\n" "$WG_PRIVKEY" | wg pubkey 2>/dev/null || true)"
          fi
          save_conf
        fi
        ;;
    esac
    ;;
  stop-all)
    stop_tor
    stop_gswarp
    stop_ovpn
    stop_gsocket
    stop_wg
    ;;
esac
exit 0
