#!/bin/bash

aembit_raw_output_chain_name=aembit_raw_output_chain
aembit_nat_output_chain_name=aembit_nat_output_chain
aembit_nat_prerouting_chain_name=aembit_nat_prerouting_chain
aembit_filter_input_chain_name=aembit_filter_input_chain

aembit_group_id=$(id --group aembit_agent_proxy)
agent_proxy_port=38080
agent_dns_port=8053
container_cidr=$AEMBIT_DOCKER_CONTAINER_CIDR
azure_platform_resources_ip=168.63.129.16

update-alternatives --set iptables /usr/sbin/iptables-legacy
update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy

custom_chains=("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, buildit 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
    iptables -t "$table_name" -D "$builtin_chain_name" -j "$custom_chain_name"

    # Delete all rules in our chain
    iptables -t "$table_name" -F "$custom_chain_name"

    # Delete custom chain
    iptables  -t "$table_name" -X "$custom_chain_name"
done

# ------ Non custom chains ------

iptables -t security -D OUTPUT -p tcp -d "${azure_platform_resources_ip}" -m owner --gid-owner "${aembit_group_id}" -j ACCEPT
