#!/bin/bash
# Firewall setup for Makenotwork production server (ufw).
#
# Rules:
#   - Allow all traffic on Tailscale interface (tailscale0)
#   - Allow SSH (port 22) from anywhere (needed for git SSH access)
#   - Allow HTTP/HTTPS (80/443) from anywhere (custom domains need direct access)
#   - Drop everything else
#
# HTTP/HTTPS is open to all because custom domains bypass Cloudflare.
# makenot.work subdomains remain protected by Caddy mTLS (Authenticated Origin Pulls):
# requests without a valid Cloudflare client cert are rejected by Caddy before
# reaching the application.

set -e

if [ "$(id -u)" -ne 0 ]; then
    echo "Error: Run as root"
    exit 1
fi

# Reset to defaults
ufw --force reset

# Default policies
ufw default deny incoming
ufw default allow outgoing

# Tailscale — unrestricted
ufw allow in on tailscale0

# SSH — open from anywhere (git clone over SSH)
ufw allow 22/tcp

# HTTP/HTTPS — open to all (custom domains need direct access)
# makenot.work is still protected by Caddy mTLS (Authenticated Origin Pulls)
ufw allow 80/tcp
ufw allow 443/tcp

# Enable
ufw --force enable
ufw status verbose

echo ""
echo "Firewall configured. SSH, HTTP, HTTPS open. makenot.work protected by Caddy mTLS."
