#!/bin/bash
# Enables wss://crivello.dyndns.org/ws -> ws://127.0.0.1:8081/ (ws-server.php) on the :443
# vhost. See ../APACHE_WSS_SETUP.md. Idempotent; backs the vhost up first and restores it if
# configtest fails. Run on the Pi:
#   sudo bash /var/www/html/WebRTC/private/enable_wss_proxy.sh
set -euo pipefail

[ "$(id -u)" -eq 0 ] || { echo "Run with sudo." >&2; exit 1; }

VHOST="$(readlink -f /etc/apache2/sites-enabled/crivello.dyndns.org.conf)"
ANCHOR='# === end StreamCam-hardening-block-v1 ==='
MARK='# === StreamCam-wss-block-v1 ==='

# mod_proxy_http (Apache >= 2.4.47) tunnels the WebSocket Upgrade itself: no mod_proxy_wstunnel.
a2query -m proxy_http >/dev/null 2>&1 || { echo "mod_proxy_http is not enabled." >&2; exit 1; }

if grep -qF "$MARK" "$VHOST"; then
    echo "wss block already present in $VHOST"
else
    [ "$(grep -cF "$ANCHOR" "$VHOST")" -eq 1 ] || { echo "Anchor not found exactly once in $VHOST" >&2; exit 1; }
    BACKUP="$VHOST.bak-$(date +%Y%m%d-%H%M%S)"
    cp -p "$VHOST" "$BACKUP"
    BLOCK="$(mktemp)"
    cat > "$BLOCK" <<'EOF'

		# === StreamCam-wss-block-v1 ===
		# Signaling over TLS: wss://crivello.dyndns.org/ws -> ws://127.0.0.1:8081/ (ws-server.php).
		# An idle tunnel is closed after Timeout (300s): every client pings well inside that
		# (viewer 7s, presence 30s, agent 30s). Deliberately only in this :443 vhost, never :80.
		ProxyPass /ws http://127.0.0.1:8081/ upgrade=websocket
		# === end StreamCam-wss-block-v1 ===
EOF
    sed -i "\|$ANCHOR|r $BLOCK" "$VHOST"
    rm -f "$BLOCK"
    if ! apache2ctl configtest; then
        cp -p "$BACKUP" "$VHOST"
        echo "configtest failed - vhost restored from $BACKUP" >&2
        exit 1
    fi
    systemctl reload apache2
    echo "wss block added (backup: $BACKUP), apache reloaded"
fi

# Local check, pinned to 127.0.0.1 so it doesn't depend on NAT hairpinning. Expect 101.
sleep 1
CODE="$(curl -s -o /dev/null -w '%{http_code}' --http1.1 --max-time 4 \
    --resolve crivello.dyndns.org:443:127.0.0.1 \
    -H 'Connection: Upgrade' -H 'Upgrade: websocket' \
    -H 'Sec-WebSocket-Version: 13' -H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==' \
    https://crivello.dyndns.org/ws || true)"
echo "Upgrade probe: HTTP $CODE (101 = proxy OK)"
