#!/bin/bash
# ==========================================
# AEA SERVER MODULE: FIREWALL COMMANDER
# VERSION: 1.10 (Auto-Rollback & Safe Sed)
# ==========================================
AEA_VERSION="1.10"
MODULE_DATE="2026-03-12"

# 1. Version check for Android app
if [ "$1" == "--version" ] || [ "$1" == "-v" ]; then
    echo "$AEA_VERSION"
    exit 0
fi

# 2. INFO MODE (Returns JSON for Android app)
if [ "$1" == "--info" ]; then
    cat << 'EOF'
{
  "module": "aea_firewall",
  "version": "1.10",
  "commands": [
    {"flag": "--ssh <port>", "desc": "Safely change SSH port with Auto-Rollback"},
    {"flag": "--open <port>", "desc": "Open specific port"},
    {"flag": "--close <port>", "desc": "Close specific port"},
    {"flag": "--state <1|0>", "desc": "1 to enable UFW, 0 to disable"}
  ]
}
EOF
    exit 0
fi

# 3. COMMAND EXECUTION MODE (Triggered from Android)
if [ "$1" == "--run" ]; then
    shift # Remove '--run' from arguments
    echo "[AEA] Executing Firewall Commander..."

    while [[ "$#" -gt 0 ]]; do
        case $1 in
            --state)
                if [ "$2" == "1" ]; then
                    echo "[AEA] Enabling UFW Firewall..."
                    ufw --force enable >/dev/null 2>&1
                elif [ "$2" == "0" ]; then
                    echo "[AEA] Disabling UFW Firewall..."
                    ufw disable >/dev/null 2>&1
                fi
                shift 2
                ;;
            --open)
                echo "[AEA] Opening port $2..."
                ufw allow "$2" >/dev/null 2>&1
                shift 2
                ;;
            --close)
                echo "[AEA] Closing port $2..."
                ufw delete allow "$2" >/dev/null 2>&1
                shift 2
                ;;
            --ssh)
                NEW_PORT="$2"
                # Find current SSH port (default to 22 if not explicitly set)
                OLD_PORT=$(sshd -T 2>/dev/null | grep -i '^port ' | awk '{print $2}')
                [ -z "$OLD_PORT" ] && OLD_PORT=22

                if [ "$NEW_PORT" != "$OLD_PORT" ]; then
                    echo "[AEA] Changing SSH port from $OLD_PORT to $NEW_PORT..."
                    
                    # A. Allow new port first
                    ufw allow "$NEW_PORT"/tcp >/dev/null 2>&1
                    
                    # --- DEAD MAN'S SWITCH (PREPARATION) ---
                    # Backup the config
                    cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

                    # B. Change sshd_config (Safe Method: Delete all 'Port' lines, add one at the end)
                    sed -i '/^[[:space:]]*#*[[:space:]]*Port /d' /etc/ssh/sshd_config
                    echo "Port $NEW_PORT" >> /etc/ssh/sshd_config
                    
                    # --- LEVEL 1: SYNTAX CHECK ---
                    if ! sshd -t >/dev/null 2>&1; then
                        echo "[AEA] CRITICAL: SSH config syntax error! Rolling back..."
                        cp /etc/ssh/sshd_config.bak /etc/ssh/sshd_config
                        ufw delete allow "$NEW_PORT"/tcp >/dev/null 2>&1
                        rm -f /etc/ssh/sshd_config.bak
                        exit 1
                    fi
                    
                    # C. Fix Ubuntu Socket & Restart SSH service
                    systemctl stop ssh.socket 2>/dev/null
                    systemctl disable ssh.socket 2>/dev/null
                    systemctl restart ssh 2>/dev/null || systemctl restart sshd 2>/dev/null
                    
                    # Wait for the service to actually try binding to the port
                    sleep 2
                    
                    # --- LEVEL 2: SERVICE HEALTH CHECK (AUTO-ROLLBACK) ---
                    if ! systemctl is-active --quiet ssh && ! systemctl is-active --quiet sshd; then
                        echo "[AEA] CRITICAL: SSH service failed to start on port $NEW_PORT! Auto-rolling back..."
                        cp /etc/ssh/sshd_config.bak /etc/ssh/sshd_config
                        systemctl restart ssh 2>/dev/null || systemctl restart sshd 2>/dev/null
                        
                        # Cleanup the messed up firewall rule
                        ufw delete allow "$NEW_PORT"/tcp >/dev/null 2>&1
                        rm -f /etc/ssh/sshd_config.bak
                        exit 1
                    fi
                    
                    # D. Success: Close old port and cleanup
                    ufw delete allow "$OLD_PORT"/tcp >/dev/null 2>&1
                    rm -f /etc/ssh/sshd_config.bak
                    echo "[AEA] SSH port successfully changed to $NEW_PORT."
                else
                    echo "[AEA] SSH is already running on port $NEW_PORT."
                fi
                shift 2
                ;;
            *)
                echo "[AEA] Unknown parameter ignored: $1"
                shift
                ;;
        esac
    done
    
    echo "[AEA] All commands executed successfully."
    exit 0
fi

# 4. INSTALLATION MODE
echo "[AEA] Installing Firewall Commander module (v$AEA_VERSION)..."

# Install UFW silently if missing
if ! command -v ufw >/dev/null 2>&1; then
    echo "[AEA] UFW not found. Installing..."
    export DEBIAN_FRONTEND=noninteractive
    apt-get update -yq >/dev/null 2>&1
    apt-get install ufw -yq >/dev/null 2>&1
fi

# Copy itself to become a global system command
MODULE_PATH="/usr/local/bin/aea_firewall"
cat "$0" > "$MODULE_PATH"
chmod +x "$MODULE_PATH"

echo "[AEA] Module successfully installed! Use 'aea_firewall --info' to see available commands."
exit 0
