#!/bin/bash
# wg-policy-cleanup.sh — Clean removal of all policy artifacts

set -uo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/wg-policy-lib.sh"

main() {
    log_info "Starting cleanup..."

    local DEF_IF
    DEF_IF="$(detect_default_if)"

    # === Base Routing Cleanup ===
    while iptables -D FORWARD -o "$WG_IF" -j ACCEPT 2>/dev/null; do :; done
    while iptables -t nat -D POSTROUTING -o "$DEF_IF" -j MASQUERADE 2>/dev/null; do :; done
    log_info "Removed base routing and NAT rules"

    # === IPv4 chain cleanup ===
    local removed=0

    while true; do
        local line=""
        line=$(iptables -nL FORWARD --line-numbers 2>/dev/null | grep "$CHAIN" | awk '{print $1}' | head -n 1 || true)
        if [[ -n "$line" ]]; then
            iptables -D FORWARD "$line" 2>/dev/null || break
            (( removed++ ))
        else
            break
        fi
    done

    if (( removed > 0 )); then
        log_info "Removed $removed FORWARD references"
    fi

    iptables -F "$CHAIN" 2>/dev/null || true
    iptables -X "$CHAIN" 2>/dev/null || true

    # Cleanup backup chain too
    iptables -F "$CHAIN_BACKUP" 2>/dev/null || true
    iptables -X "$CHAIN_BACKUP" 2>/dev/null || true

    # === IPv6 chain cleanup ===
    if command -v ip6tables &>/dev/null; then
        while true; do
            local line6=""
            line6=$(ip6tables -nL FORWARD --line-numbers 2>/dev/null | grep "$CHAIN" | awk '{print $1}' | head -n 1 || true)
            if [[ -n "$line6" ]]; then
                ip6tables -D FORWARD "$line6" 2>/dev/null || break
            else
                break
            fi
        done
        ip6tables -F "$CHAIN" 2>/dev/null || true
        ip6tables -X "$CHAIN" 2>/dev/null || true
        ip6tables -F "$CHAIN_BACKUP" 2>/dev/null || true
        ip6tables -X "$CHAIN_BACKUP" 2>/dev/null || true
    fi

    # === ipset cleanup ===
    destroy_ipset "$IPSET_V4" 2>/dev/null || true
    destroy_ipset "$IPSET_V6" 2>/dev/null || true
    destroy_ipset "${IPSET_V4}_bak" 2>/dev/null || true
    destroy_ipset "${IPSET_V6}_bak" 2>/dev/null || true

    # === Lock cleanup ===
    rm -f "$LOCK_FILE" 2>/dev/null || true

    log_info "Cleanup complete"
}

main "$@"
