#!/bin/bash
# vpn-torrent.sh
# Connects OpenVPN and routes only torrent client traffic through VPN

# --- CONFIG ---
OVPN_FILE="/var/www/test/files/hu69.nordvpn.com.tcp.ovpn"
TORRENT_PORT=12345
VPN_TABLE="vpn"
VPN_IFACE="tun0"   # Will try to detect if tun0 exists
# ----------------

# 1. Ensure VPN routing table exists
if ! grep -q "^200 $VPN_TABLE" /etc/iproute2/rt_tables; then
    echo "200 $VPN_TABLE" | sudo tee -a /etc/iproute2/rt_tables
fi

# 2. Connect OpenVPN in background
echo "[*] Connecting to OpenVPN..."
sudo openvpn --config "$OVPN_FILE" --route-nopull --daemon

# Wait a few seconds for the VPN interface to appear
sleep 5

# Detect VPN interface automatically if tun0 not up
if ! ip addr show "$VPN_IFACE" > /dev/null 2>&1; then
    VPN_IFACE=$(ip addr | grep tun | awk -F: '/tun/{print $2}' | head -n1 | xargs)
    if [ -z "$VPN_IFACE" ]; then
        echo "[-] Could not detect VPN interface. Exiting."
        exit 1
    fi
fi
echo "[*] VPN interface detected: $VPN_IFACE"

# 3. Mark torrent traffic
echo "[*] Marking torrent traffic on port $TORRENT_PORT..."
sudo iptables -t mangle -A OUTPUT -p tcp --dport $TORRENT_PORT -j MARK --set-mark 1
sudo iptables -t mangle -A OUTPUT -p udp --dport $TORRENT_PORT -j MARK --set-mark 1

# 4. Add policy-based routing for marked traffic
echo "[*] Setting up routing table '$VPN_TABLE'..."
sudo ip rule add fwmark 1 table $VPN_TABLE
sudo ip route add default dev $VPN_IFACE table $VPN_TABLE

echo "[+] Setup complete!"
echo "    - Torrent traffic (port $TORRENT_PORT) -> VPN"
echo "    - All other traffic -> ISP (default route)"
echo "    - SSH connections safe"
