#!/bin/bash
# Manage Core Nest ports using iptables
# Usage: sudo ./iptables.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 [ ! -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 (iptables) ==="
else
    echo "=== Closing Core Nest Ports (iptables) ==="
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
        # Open port
        if iptables -C INPUT -p tcp --dport "$port" -j ACCEPT 2>/dev/null; then
            echo "  Port $port: Already open"
        else
            echo "  Port $port: Opening..."
            iptables -I INPUT -p tcp --dport "$port" -j ACCEPT
            echo "  Port $port: ✓ Opened"
        fi
    else
        # Close port
        if iptables -C INPUT -p tcp --dport "$port" -j ACCEPT 2>/dev/null; then
            echo "  Port $port: Closing..."
            iptables -D INPUT -p tcp --dport "$port" -j ACCEPT
            echo "  Port $port: ✓ Closed"
        else
            echo "  Port $port: Already closed"
        fi
    fi
done < "$PORTS_FILE"

echo ""
echo "=== Done ==="

if [ "$ACTION" = "open" ]; then
    echo ""
    echo "Note: iptables rules are not persistent across reboots."
    echo "To make persistent, install iptables-persistent:"
    echo "  apt-get install iptables-persistent"
    echo "  netfilter-persistent save"
fi
