#!/bin/bash
set -euo pipefail

# ============================================================
#  RadioRations UFW — Tailscale remote + RFC1918 LAN admin
#  RF users (packet/APRS) do NOT need these ports; they use radio.
#  Safe to run standalone (no lib.sh required).
# ============================================================

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
log()  { echo -e "${GREEN}[+]${NC} $*"; }
warn() { echo -e "${YELLOW}[!]${NC} $*"; }

log "Installing and configuring UFW..."

sudo apt-get install -y ufw

# Reset to a known state (non-interactive)
sudo ufw --force reset

sudo ufw default deny incoming
sudo ufw default allow outgoing

# --- SSH break-glass: all RFC1918 + Tailscale CGNAT ---
for cidr in 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 100.64.0.0/10; do
    sudo ufw allow from "$cidr" to any port 22 proto tcp comment "SSH ${cidr}"
done

# --- Ham admin UIs: RFC1918 (home LAN / field router) ---
for cidr in 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16; do
    sudo ufw allow from "$cidr" to any port 8080 proto tcp comment "Graywolf ${cidr}"
    sudo ufw allow from "$cidr" to any port 8081 proto tcp comment "Pat ${cidr}"
    sudo ufw allow from "$cidr" to any port 8090 proto tcp comment "LinBPQ-web ${cidr}"
    sudo ufw allow from "$cidr" to any port 8010 proto tcp comment "LinBPQ-telnet ${cidr}"
done

# --- Same UIs: Tailscale CGNAT (remote admin) ---
TS="100.64.0.0/10"
sudo ufw allow from "$TS" to any port 8080 proto tcp comment "Graywolf Tailscale"
sudo ufw allow from "$TS" to any port 8081 proto tcp comment "Pat Tailscale"
sudo ufw allow from "$TS" to any port 8090 proto tcp comment "LinBPQ-web Tailscale"
sudo ufw allow from "$TS" to any port 8010 proto tcp comment "LinBPQ-telnet Tailscale"

# Modem / gpsd stay localhost-only — no UFW rules needed

sudo ufw --force enable
sudo ufw status numbered

log "UFW enabled: SSH + admin UIs on RFC1918 + Tailscale; default deny elsewhere"
warn "RF (packet/APRS) is unaffected — those paths are not TCP through UFW"
echo "  Review: sudo ufw status verbose"
