#!/usr/bin/env bash
# One-time setup of the WireGuard hub that customers' MikroTik routers dial into.
# Run as root on the SAME server that runs the billing app (the app reaches routers through this tunnel).
#
#   sudo ./deploy/wireguard-hub.sh billing.example.com            # public host name or IP routers will connect to
#   sudo WG_PORT=51820 ./deploy/wireguard-hub.sh 203.0.113.10 10.99.0.0/16 10.99.0.1
#
# Safe to re-run: keys are kept, config files are rewritten.
set -euo pipefail

ENDPOINT_HOST="${1:?usage: $0 <public-host-or-ip> [pool-cidr] [server-tunnel-ip]}"
POOL="${2:-10.99.0.0/16}"
SERVER_IP="${3:-10.99.0.1}"
PORT="${WG_PORT:-51820}"
IFACE="${WG_IFACE:-wg0}"
TUNNEL_HTTP_PORT="${TUNNEL_HTTP_PORT:-8081}"
PREFIX="${POOL#*/}"
DIR=/etc/wireguard

[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
[[ "$ENDPOINT_HOST" =~ ^[A-Za-z0-9.-]+$ ]] || { echo "bad host name"; exit 1; }
[[ "$POOL" =~ ^[0-9.]+/[0-9]+$ && "$SERVER_IP" =~ ^[0-9.]+$ ]] || { echo "bad pool or server ip"; exit 1; }

export DEBIAN_FRONTEND=noninteractive
command -v wg >/dev/null || apt-get install -y -qq wireguard
command -v nft >/dev/null || apt-get install -y -qq nftables

umask 077
mkdir -p "$DIR"
[ -f "$DIR/server.key" ] || wg genkey > "$DIR/server.key"
wg pubkey < "$DIR/server.key" > "$DIR/server.pub"

# Remote access to routers (WebFig / Winbox / API through this host) needs packet forwarding
echo 'net.ipv4.ip_forward=1' > /etc/sysctl.d/99-sb-forward.conf
sysctl -q -w net.ipv4.ip_forward=1

# Isolation: routers belong to different tenants. They may talk to the server's tunnel address on the config port only,
# never to each other, never to the server's other services, and never beyond the server. (Server -> router is unrestricted.)
cat > "$DIR/sb-firewall.nft" <<EOF
table inet sb_wg
delete table inet sb_wg
table inet sb_wg {
  chain input {
    type filter hook input priority -10; policy accept;
    iifname "$IFACE" ct state established,related accept
    iifname "$IFACE" ip daddr $SERVER_IP tcp dport $TUNNEL_HTTP_PORT accept
    iifname "$IFACE" ip daddr $SERVER_IP udp dport { 1812, 1813 } accept      # built-in RADIUS (bin/radius_server.php)
    iifname "$IFACE" ip daddr $SERVER_IP icmp type echo-request accept
    iifname "$IFACE" drop
  }
  chain forward {
    type filter hook forward priority -10; policy accept;
    iifname "$IFACE" drop
    oifname "$IFACE" ct state established,related accept
    oifname "$IFACE" ct status dnat accept
    oifname "$IFACE" drop
  }
}
EOF

# [Interface] part only: bin/wg_sync.php appends one [Peer] per router and writes the live $IFACE.conf
cat > "$DIR/$IFACE.base.conf" <<EOF
[Interface]
Address = $SERVER_IP/$PREFIX
ListenPort = $PORT
PrivateKey = $(cat "$DIR/server.key")
PostUp = nft -f $DIR/sb-firewall.nft
PostUp = test -f $DIR/sb-forward.nft && nft -f $DIR/sb-forward.nft || true
PostDown = nft delete table inet sb_wg
PostDown = nft delete table ip sb_fwd 2>/dev/null || true
EOF
[ -f "$DIR/$IFACE.conf" ] || cp "$DIR/$IFACE.base.conf" "$DIR/$IFACE.conf"
chmod 600 "$DIR"/*.conf "$DIR/server.key"

systemctl enable --now "wg-quick@$IFACE" >/dev/null
systemctl restart "wg-quick@$IFACE"

# ufw: its forward chain silently drops the remote-access traffic unless these rules exist, so add them here.
if command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -q "Status: active"; then
  ufw allow "$PORT/udp" >/dev/null || true
  ufw allow in on "$IFACE" to "$SERVER_IP" port "$TUNNEL_HTTP_PORT" proto tcp >/dev/null || true
  ufw allow in on "$IFACE" to "$SERVER_IP" port 1812,1813 proto udp >/dev/null || true      # RADIUS
  ufw allow 20000:60000/tcp >/dev/null || true
  PUBIF=$(ip -4 route show default | awk '{print $5; exit}')
  [ -n "$PUBIF" ] && ufw route allow in on "$PUBIF" out on "$IFACE" to "$POOL" proto tcp port 80,8291,8728 >/dev/null || true
  echo "ufw: opened UDP $PORT, tunnel http $TUNNEL_HTTP_PORT, 20000:60000/tcp and the forward route (public iface: ${PUBIF:-unknown})"
fi

cat <<EOF

WireGuard hub is up on $IFACE ($SERVER_IP/$PREFIX, UDP $PORT).

1) Open UDP $PORT to the internet (ufw: ufw allow $PORT/udp). If you use ufw also run:
     ufw allow in on $IFACE to $SERVER_IP port $TUNNEL_HTTP_PORT proto tcp
   Remote access ports (the panel shows each router's own ports; default range starts at 20000):
     ufw allow 20000:60000/tcp                       # or only the ports of your routers, ideally from your own IP addresses
     ufw route allow in on <public-interface> out on $IFACE to $POOL proto tcp port 80,8291,8728

2) Add this to config/config.php:
     'wireguard' => [
         'endpoint'          => '$ENDPOINT_HOST:$PORT',
         'server_public_key' => '$(cat "$DIR/server.pub")',
         'pool'              => '$POOL',
         'server_ip'         => '$SERVER_IP',
         'interface'         => '$IFACE',
         'base_conf'         => '$DIR/$IFACE.base.conf',
         'conf'              => '$DIR/$IFACE.conf',
         'tunnel_url'        => 'http://$SERVER_IP:$TUNNEL_HTTP_PORT',
     ],

3) Serve the config scripts on the tunnel address only: see deploy/nginx-tunnel.conf or deploy/apache-tunnel.conf
   (the web server must start after $IFACE is up: ip_nonlocal_bind or After=wg-quick@$IFACE.service).

4) Root cron, every minute, so new routers get a peer:
     * * * * * root /usr/bin/php $(cd "$(dirname "$0")/.." && pwd)/bin/wg_sync.php >> /var/log/sb-wg-sync.log 2>&1
   Preview what it would write first:  php bin/wg_sync.php --dry-run
EOF
