#!/bin/bash

chain_name=aembit-redirect-chain
prerouting_chain_name=AEMBIT-PREROUTING
aembit_group_id=$(id --group aembit_agent_proxy)
agent_proxy_port=38080
agent_dns_port=8053
container_cidr=$AEMBIT_DOCKER_CONTAINER_CIDR

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

iptables -t raw -D OUTPUT -p udp --dport 53 -m owner --gid-owner "${aembit_group_id}" -j NOTRACK

iptables -t raw -D OUTPUT -p udp -s 127.0.0.53 --sport 53 -j NOTRACK

# Delete our chain reference from output chain
iptables -t nat -D OUTPUT -j "${chain_name}"

# Delete all rules in our chain
iptables -t nat -F "${chain_name}"

# Delete custom chain
iptables  -t nat -X "${chain_name}"

# Delete prerouting rule, reference, and chain
if [ -n $container_cidr ]; then
    iptables  -t nat -F "${prerouting_chain_name}"
    iptables -t nat -D PREROUTING -j "${prerouting_chain_name}"
    iptables -t nat -X "${prerouting_chain_name}"
fi

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