#!/bin/bash

aembit_raw_prerouting_chain_name=aembit_raw_prerouting_chain
aembit_raw_output_chain_name=aembit_raw_output_chain
aembit_nat_output_chain_name=aembit_nat_output_chain
aembit_filter_input_chain_name=aembit_filter_input_chain

FIREWALL_CMD="firewall-cmd --quiet"

custom_chains=("raw,PREROUTING,$aembit_raw_prerouting_chain_name" "raw,OUTPUT,$aembit_raw_output_chain_name" "nat,OUTPUT,$aembit_nat_output_chain_name" "nat,PREROUTING,$aembit_nat_prerouting_chain_name" "filter,INPUT,$aembit_filter_input_chain_name")

for custom_chain in "${custom_chains[@]}"; do
    # Split to table, built-in chain and custom chain name
    IFS=',' read -r -a custom_chain_parts <<< "$custom_chain"

    table_name="${custom_chain_parts[0]}"
    builtin_chain_name="${custom_chain_parts[1]}"
    custom_chain_name="${custom_chain_parts[2]}"

    # Delete our chain reference from output chain
    ${FIREWALL_CMD} --direct --remove-rule ipv4 "$table_name" "$builtin_chain_name" 0 -j "$custom_chain_name"

    # Delete all rules in our chain
    ${FIREWALL_CMD} --direct --remove-rules ipv4 "$table_name" "$custom_chain_name"

    # Delete custom chain
    ${FIREWALL_CMD} --direct --remove-chain ipv4 "$table_name" "$custom_chain_name"
done

# remove the rich rule for accepting udp responses on an untracked connection.
${FIREWALL_CMD} --remove-rich-rule='rule source-port port=53 protocol=udp accept'

# make it permanent
${FIREWALL_CMD} --runtime-to-permanent

# reload firewalld 
${FIREWALL_CMD} --reload
