#!/bin/sh
# Installs or upgrades the Netbine tunnel relay as the systemd service `netbine-tunnel`.
# It replaces the doctor-only `netbine-relay` service and keeps answering netbine-doctor probes
# with the existing doctor key. Usage (on the VPS, next to the binary):  sudo sh install-tunnel.sh
set -eu

[ "$(id -u)" -eq 0 ] || { echo "run as root (sudo)"; exit 1; }
BIN_SRC="$(dirname "$0")/netbine-relay"
[ -f "$BIN_SRC" ] || { echo "netbine-relay binary not found next to this script"; exit 1; }

CONFIG=/etc/netbine/tunnel.toml
LIB=/usr/local/lib/netbine
WAN_IF="$(ip -4 route show default | awk '{print $5; exit}')"
PUBLIC_IP="$(ip -4 route get 1.1.1.1 | sed -n 's/.* src \([0-9.]*\).*/\1/p')"
[ -n "$WAN_IF" ] && [ -n "$PUBLIC_IP" ] || { echo "could not detect the internet interface"; exit 1; }

systemctl stop netbine-tunnel 2>/dev/null || true
systemctl disable --now netbine-relay 2>/dev/null || true
install -m 755 "$BIN_SRC" /usr/local/bin/netbine-relay
install -d -m 700 /etc/netbine
install -d -m 755 "$LIB"

if [ ! -f "$CONFIG" ]; then
    DOCTOR_KEY=""
    [ -f /etc/netbine/relay.env ] && DOCTOR_KEY="$(sed -n 's/^NETBINE_KEY=//p' /etc/netbine/relay.env)"
    if [ -n "$DOCTOR_KEY" ]; then
        netbine-relay init --config "$CONFIG" --bind "$PUBLIC_IP" --doctor-key "$DOCTOR_KEY" >/dev/null
    else
        netbine-relay init --config "$CONFIG" --bind "$PUBLIC_IP" >/dev/null
    fi
else
    # Keeps keys and clients; adds a doctor key to configs from older versions.
    netbine-relay init --config "$CONFIG"
fi
PORTS="$(netbine-relay ports --config "$CONFIG")"

cat > "$LIB/net-up.sh" <<EOF
#!/bin/sh
set -e
# A queue per core lets the relay use every core for traffic back to the players.
ip tuntap add dev nb0 mode tun multi_queue 2>/dev/null || ip tuntap add dev nb0 mode tun 2>/dev/null || true
ip addr replace 10.77.0.1/16 dev nb0
ip link set nb0 up mtu 1420 txqueuelen 1000
sysctl -q -w net.ipv4.ip_forward=1 net.core.rmem_max=8388608 net.core.wmem_max=8388608 || true
if command -v nft >/dev/null; then
    nft delete table ip netbine 2>/dev/null || true
    nft -f - <<NFT
table ip netbine {
    chain postrouting {
        type nat hook postrouting priority srcnat; policy accept;
        ip saddr 10.77.0.0/16 oifname "$WAN_IF" masquerade
    }
    chain forward {
        type filter hook forward priority mangle; policy accept;
        # Game UDP may use the full tunnel MTU; TCP segments stay small enough for every link.
        tcp flags syn tcp option maxseg size > 1240 tcp option maxseg size set 1240
    }
}
NFT
else
    iptables -t nat -C POSTROUTING -s 10.77.0.0/16 -o $WAN_IF -j MASQUERADE 2>/dev/null ||
        iptables -t nat -A POSTROUTING -s 10.77.0.0/16 -o $WAN_IF -j MASQUERADE
    iptables -t mangle -C FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --set-mss 1240 2>/dev/null ||
        iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --set-mss 1240
fi
# Hosts that drop incoming traffic by default (ufw, cloud images) would never see a handshake.
if command -v iptables >/dev/null; then
    for p in $(echo "$PORTS" | tr "," " "); do
        iptables -C INPUT -p udp --dport \$p -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport \$p -j ACCEPT
    done
    iptables -C FORWARD -i nb0 -j ACCEPT 2>/dev/null || iptables -I FORWARD -i nb0 -j ACCEPT
    iptables -C FORWARD -o nb0 -j ACCEPT 2>/dev/null || iptables -I FORWARD -o nb0 -j ACCEPT
fi
EOF

cat > "$LIB/net-down.sh" <<'EOF'
#!/bin/sh
nft delete table ip netbine 2>/dev/null || true
ip link del nb0 2>/dev/null || true
if command -v iptables >/dev/null; then
    iptables -D FORWARD -i nb0 -j ACCEPT 2>/dev/null || true
    iptables -D FORWARD -o nb0 -j ACCEPT 2>/dev/null || true
fi
EOF
chmod 755 "$LIB/net-up.sh" "$LIB/net-down.sh"

cat > /etc/systemd/system/netbine-tunnel.service <<EOF
[Unit]
Description=Netbine tunnel relay
After=network-online.target
Wants=network-online.target

[Service]
ExecStartPre=$LIB/net-up.sh
ExecStart=/usr/local/bin/netbine-relay tunnel --config $CONFIG
ExecStopPost=$LIB/net-down.sh
Restart=always
RestartSec=2
# Forwarding game packets must not wait behind other work on a small shared VPS.
Nice=-10

[Install]
WantedBy=multi-user.target
EOF

# Open the tunnel ports in the host firewall too, so they stay open across firewall reloads.
if command -v ufw >/dev/null && ufw status 2>/dev/null | grep -q "Status: active"; then
    ufw allow "$PORTS/udp" comment netbine >/dev/null
    ufw route allow in on nb0 out on "$WAN_IF" comment netbine >/dev/null
    echo "ufw: opened UDP $PORTS and allowed forwarding from the tunnel."
fi
if command -v firewall-cmd >/dev/null && firewall-cmd --state >/dev/null 2>&1; then
    for p in $(echo "$PORTS" | tr "," " "); do
        firewall-cmd --permanent --add-port="$p/udp" >/dev/null
    done
    firewall-cmd --permanent --zone=trusted --add-interface=nb0 >/dev/null 2>&1 || true
    firewall-cmd --reload >/dev/null
    echo "firewalld: opened UDP $PORTS."
fi

# Allow a PC right away when the installer was given its key (app "Install command" / SSH setup).
if [ -n "${NETBINE_CLIENT_KEY:-}" ]; then
    netbine-relay add-client --config "$CONFIG" --name "${NETBINE_CLIENT_NAME:-pc}" --public-key "$NETBINE_CLIENT_KEY"
fi

# Join a panel when the panel's Add server page gave a one-time token.
if [ -n "${NETBINE_PANEL_URL:-}" ] && [ -n "${NETBINE_PANEL_TOKEN:-}" ]; then
    netbine-relay panel-enroll --config "$CONFIG" --address "$PUBLIC_IP" --name "${NETBINE_NAME:-$(hostname)}"
fi

systemctl daemon-reload
systemctl enable netbine-tunnel >/dev/null 2>&1
systemctl restart netbine-tunnel
sleep 1
systemctl --no-pager --lines=8 status netbine-tunnel || true

echo
echo "If your provider has a cloud firewall (Vultr firewall group, AWS security group, Oracle"
echo "security list...), allow UDP $PORTS there as well."

RELAY_KEY="$(sed -n 's/^public_key = "\(.*\)"/\1/p' "$CONFIG")"
CODE="$(netbine-relay connection-code --config "$CONFIG" --address "$PUBLIC_IP" --name "${NETBINE_NAME:-$(hostname)}")"
VERSION="$(netbine-relay --version | awk '{print $2}')"

echo
echo "Netbine relay $VERSION is running on $PUBLIC_IP (interface $WAN_IF)."
echo
echo "Connection code for the Netbine app (Servers > Add server > Connection code):"
echo "  $CODE"
echo
echo "For the command-line client instead: relay public key $RELAY_KEY"
if [ -z "${NETBINE_CLIENT_KEY:-}" ]; then
    echo
    echo "The app shows the command that allows your PC here, like:"
    echo "  sudo netbine-relay add-client --name gaming-pc --public-key <client key>"
    echo "  sudo systemctl restart netbine-tunnel"
fi
# Machine-readable results for the app's SSH setup.
echo "NETBINE_RELAY_VERSION=$VERSION"
echo "NETBINE_CONNECTION_CODE=$CODE"
