#!/bin/bash

# Clear all LibrePortal-managed firewall rules
firewallClearLibrePortalRules()
{
    local total_cleared=0
    
    if [[ $EUID -eq 0 ]] && command -v ufw-docker &> /dev/null; then
        local libreportal_rules=$(runSystem ufw-docker list 2>/dev/null | grep -E "(allow|deny)" || echo "")
        if [[ -n "$libreportal_rules" ]]; then
            echo "$libreportal_rules" | while read -r rule_line; do
                if [[ $rule_line =~ (allow|deny)\ ([^[:space:]]+)\ ([^[:space:]]+) ]]; then
                    local action="${BASH_REMATCH[1]}"
                    local container="${BASH_REMATCH[2]}"
                    local port_spec="${BASH_REMATCH[3]}"
                    
                    # Only clear LibrePortal app rules (not system rules)
                    if [[ -d "$containers_dir/$container" ]]; then
                        local result=$(runSystem ufw-docker delete "$action" "$container" "$port_spec" 2>&1)
                        if [[ $? -eq 0 ]]; then
                            ((total_cleared++))
                            isSuccessful "Cleared: $action $container $port_spec"
                        else
                            isNotice "Failed to clear: $action $container $port_spec"
                        fi
                    fi
                fi
            done
        else
            isSuccessful "No UFW-Docker rules found"
        fi
        
    elif command -v ufw &> /dev/null; then
        local libreportal_rules=$(runSystem ufw status numbered 2>/dev/null | grep -E "ALLOW.*LibrePortal" || echo "")
        
        if [[ -n "$libreportal_rules" ]]; then
            echo "$libreportal_rules" | while read -r rule_line; do
                if [[ $rule_line =~ ^\[([0-9]+)\]\ (ALLOW|DENY)\ (.*)\ \(LibrePortal\)$ ]]; then
                    local rule_num="${BASH_REMATCH[1]}"
                    local action="${BASH_REMATCH[2]}"
                    local port_spec="${BASH_REMATCH[3]}"
                    
                    local result=$(runSystem ufw --force delete "$rule_num" 2>&1)
                    if [[ $? -eq 0 ]]; then
                        ((total_cleared++))
                        isNotice "Cleared rule #$rule_num: $action $port_spec"
                    else
                        isNotice "Failed to clear rule #$rule_num: $action $port_spec"
                    fi
                fi
            done
        else
            isSuccessful "No LibrePortal UFW rules found"
        fi
    else
        isNotice "No firewall management available"
    fi
    
    isSuccessful "Cleared $total_cleared LibrePortal firewall rules"
}
