#!/bin/bash
# CoverConnect TUN helper — runs as root (started through pkexec by the app).
#
#   cc-tun run <server-ipv4> <xray-socks-port>
#
# Creates the TUN device, starts tun2socks (forwarding into Xray's local SOCKS inbound), routes all
# traffic through it, and keeps running until its stdin is closed or receives "stop" — the app holds
# the other end of that pipe, so if the app crashes or is killed, this script notices EOF and removes
# every route/device it added. Nothing is left behind.
set -u
export PATH=/usr/sbin:/usr/bin:/sbin:/bin

DIR=$(dirname "$(readlink -f "$0")")
DEV=cctun0
ADDR=198.18.0.1/15

[ "${1:-}" = "run" ] || { echo "usage: cc-tun run <server-ipv4> <socks-port>" >&2; exit 2; }
SERVER=${2:-}
PORT=${3:-}
[[ "$SERVER" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] || { echo "bad server address" >&2; exit 2; }
[[ "$PORT" =~ ^[0-9]{3,5}$ ]] && [ "$PORT" -ge 1024 ] && [ "$PORT" -le 65535 ] || { echo "bad port" >&2; exit 2; }
[ -x "$DIR/tun2socks" ] || { echo "tun2socks missing" >&2; exit 2; }

# Current default route (gateway + interface) — the VPN server itself must keep using it,
# otherwise Xray's own connection to the server would loop back into the tunnel.
read -r GW PHYS < <(ip -4 route show default | awk 'NR==1{g="";d="";for(i=1;i<=NF;i++){if($i=="via")g=$(i+1);if($i=="dev")d=$(i+1)};print (g==""?"-":g), d}')
if [ -z "${PHYS:-}" ]; then echo "NOGATEWAY"; exit 3; fi

TPID=""
SERVER_ROUTE_ADDED=0
cleanup() {
    trap - EXIT INT TERM HUP
    ip route del 0.0.0.0/1 dev "$DEV" 2>/dev/null
    ip route del 128.0.0.0/1 dev "$DEV" 2>/dev/null
    ip -6 route del unreachable ::/1 2>/dev/null
    ip -6 route del unreachable 8000::/1 2>/dev/null
    [ "$SERVER_ROUTE_ADDED" = 1 ] && ip route del "$SERVER/32" 2>/dev/null
    [ -n "$TPID" ] && kill "$TPID" 2>/dev/null && wait "$TPID" 2>/dev/null
    command -v resolvectl >/dev/null && resolvectl revert "$DEV" 2>/dev/null
    ip link del "$DEV" 2>/dev/null
}
trap cleanup EXIT
trap 'exit 0' INT TERM HUP

# A stale device from a crashed run (shouldn't happen, but harmless to be sure).
ip link del "$DEV" 2>/dev/null

# 1. Keep the VPN server reachable over the real network.
if [ "$GW" = "-" ]; then ip route replace "$SERVER/32" dev "$PHYS"; else ip route replace "$SERVER/32" via "$GW" dev "$PHYS"; fi
SERVER_ROUTE_ADDED=1

# 2. TUN device + address.
ip tuntap add mode tun dev "$DEV" || { echo "cannot create TUN device (is /dev/net/tun available?)" >&2; exit 4; }
ip addr add "$ADDR" dev "$DEV"
ip link set dev "$DEV" up

# 3. tun2socks → Xray's SOCKS inbound.
"$DIR/tun2socks" --device "tun://$DEV" --proxy "socks5://127.0.0.1:$PORT" --loglevel warning &
TPID=$!
sleep 0.7
kill -0 "$TPID" 2>/dev/null || { echo "tun2socks exited immediately" >&2; TPID=""; exit 5; }

# 4. Everything through the tunnel. Two /1 routes beat the existing /0 default without touching it,
#    so removing them is all it takes to restore the normal network. IPv6 is made unreachable so apps
#    fall back to IPv4 immediately instead of leaking around the tunnel.
ip route add 0.0.0.0/1 dev "$DEV"
ip route add 128.0.0.0/1 dev "$DEV"
ip -6 route add unreachable ::/1 2>/dev/null
ip -6 route add unreachable 8000::/1 2>/dev/null

# 5. DNS through the tunnel (systemd-resolved; without it the system resolver is used as-is).
if command -v resolvectl >/dev/null 2>&1; then
    resolvectl dns "$DEV" 8.8.8.8 1.1.1.1 2>/dev/null
    resolvectl domain "$DEV" '~.' 2>/dev/null
    resolvectl default-route "$DEV" yes 2>/dev/null
fi

echo READY

# Stay alive until the app says stop / closes the pipe, or tun2socks dies.
while true; do
    kill -0 "$TPID" 2>/dev/null || { echo "tun2socks stopped unexpectedly" >&2; exit 6; }
    if read -r -t 1 line; then
        [ "$line" = "stop" ] && break
    else
        [ $? -le 128 ] && break   # EOF → the app is gone
    fi
done
exit 0
