#!/bin/sh

set -eu

echo "======================================"
echo " UDP2RAW WireGuard Client Setup"
echo "======================================"

VPS_HOST="146.59.230.190"
UDP2RAW_REMOTE_PORT="444"

LOCAL_WG_PORT="4999"

UDP2RAW_PASSWORD="test123"
RAW_MODE="faketcp"

WG_MTU="1240"

INIT_SCRIPT="/etc/init.d/udp2raw-wg"

echo ""
echo "[1/10] Checking udp2raw binary..."

if ! command -v udp2raw >/dev/null 2>&1; then
    echo "ERROR: udp2raw binary is missing"
    exit 10
fi

echo "udp2raw binary found:"
command -v udp2raw

echo ""
echo "[2/10] Stopping existing service if present..."

if [ -f "$INIT_SCRIPT" ]; then
    /etc/init.d/udp2raw-wg stop || true
fi

pkill -f "/usr/bin/udp2raw" || true

sleep 1

echo ""
echo "[3/10] Writing init.d service..."

cat > "$INIT_SCRIPT" <<EOF
#!/bin/sh /etc/rc.common

START=95
STOP=10
USE_PROCD=1

start_service() {
    procd_open_instance

    procd_set_param command \\
        /usr/bin/udp2raw \\
        -c \\
        -l 127.0.0.1:${LOCAL_WG_PORT} \\
        -r ${VPS_HOST}:${UDP2RAW_REMOTE_PORT} \\
        --raw-mode ${RAW_MODE} \\
        -k ${UDP2RAW_PASSWORD}

    procd_set_param respawn
    procd_set_param stdout 1
    procd_set_param stderr 1

    procd_close_instance
}
EOF

chmod +x "$INIT_SCRIPT"

echo ""
echo "[4/10] Enabling service..."

/etc/init.d/udp2raw-wg enable

echo ""
echo "[5/10] Starting service..."

/etc/init.d/udp2raw-wg restart

sleep 3

echo ""
echo "[6/10] Updating WireGuard endpoint and MTU..."

if ! uci show network.wgserver >/dev/null 2>&1; then
    echo "ERROR: WireGuard peer section network.wgserver was not found"
    exit 30
fi

if ! uci show network.wg0 >/dev/null 2>&1; then
    echo "ERROR: WireGuard interface section network.wg0 was not found"
    exit 31
fi

uci set network.wgserver.endpoint_host='127.0.0.1'
uci set network.wgserver.endpoint_port="${LOCAL_WG_PORT}"
uci set network.wg0.mtu="${WG_MTU}"

uci commit network

echo ""
echo "[7/10] Restarting WireGuard interface..."

ifdown wg0 || true
sleep 2
ifup wg0 || true
sleep 5

echo ""
echo "[8/10] Checking udp2raw process..."

if pgrep -af "^/usr/bin/udp2raw" >/dev/null 2>&1; then
    echo "udp2raw process running:"
    pgrep -af "^/usr/bin/udp2raw"
else
    echo "ERROR: udp2raw process not running"
    exit 20
fi

echo ""
echo "[9/10] Checking local listener..."

if netstat -ln 2>/dev/null | grep -q "127.0.0.1:${LOCAL_WG_PORT}"; then
    echo "Local listener active on 127.0.0.1:${LOCAL_WG_PORT}"
else
    echo "WARNING: Could not confirm local listener"
fi

echo ""
echo "[10/10] Testing connectivity..."

ping -c 2 -W 2 "${VPS_HOST}" || true

echo ""
echo "WireGuard endpoint:"
uci get network.wgserver.endpoint_host
uci get network.wgserver.endpoint_port

echo ""
echo "WireGuard MTU:"
uci get network.wg0.mtu || true

echo ""
echo "WireGuard status:"
wg show wg0 || true

echo ""
echo "======================================"
echo " UDP2RAW setup completed successfully"
echo "======================================"