#!/bin/bash
# Manage Core Nest ports using ufw
# Usage: sudo ./ufw.sh [open|close]

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PORTS_FILE="$SCRIPT_DIR/ports"

if [ "$EUID" -ne 0 ]; then
    echo "Error: This script must be run as root (use sudo)"
    exit 1
fi

if ! command -v ufw &> /dev/null; then
    echo "Error: ufw is not installed"
    exit 1
fi

if [ ! -f "$PORTS_FILE" ]; then
    echo "Error: ports file not found at $PORTS_FILE"
    exit 1
fi

ACTION="${1:-}"
if [ "$ACTION" != "open" ] && [ "$ACTION" != "close" ]; then
    echo "Usage: sudo $0 [open|close]"
    exit 1
fi

if [ "$ACTION" = "open" ]; then
    echo "=== Opening Core Nest Ports (ufw) ==="
else
    echo "=== Closing Core Nest Ports (ufw) ==="
fi
echo ""

# Read ports and apply action
while IFS= read -r line || [ -n "$line" ]; do
    # Skip comments and empty lines
    [[ "$line" =~ ^#.*$ ]] && continue
    [[ -z "$line" ]] && continue

    port=$(echo "$line" | tr -d ' ')

    if [ "$ACTION" = "open" ]; then
        echo "  Port $port: Opening..."
        ufw allow "$port/tcp" comment "Core Nest"
        echo "  Port $port: ✓ Opened"
    else
        echo "  Port $port: Closing..."
        ufw delete allow "$port/tcp" 2>/dev/null || echo "  Port $port: Not found (already closed)"
        echo "  Port $port: ✓ Closed"
    fi
done < "$PORTS_FILE"

echo ""
echo "=== Done ==="
echo ""
echo "Reload ufw to apply changes:"
echo "  ufw reload"
