#!/bin/bash

chain_name=aembit-redirect-chain
aembit_user_id=$(id --user aembit)
agent_proxy_port=38080
agent_dns_port=8053

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 --uid-owner "${aembit_user_id}" -j NOTRACK

# Ignore (return to the main chain) all packets from our agent proxy
iptables -t nat -D "${chain_name}" -m owner --uid-owner "${aembit_user_id}" -j RETURN

# Ignore TCP loopback
iptables -t nat -D "${chain_name}" -p tcp -o lo -j RETURN

# Redirect everything else to agent proxy port port
iptables -t nat -D "${chain_name}" -p  tcp -j REDIRECT --to-port "${agent_proxy_port}"

# Redirect DNS traffic to agent proxy DNS port
iptables -t nat -D "${chain_name}" -p udp --dport 53 -m owner --uid-owner "$(id --user systemd-resolve)" -j RETURN
iptables -t nat -D "${chain_name}" -p udp --dport 53 -j REDIRECT --to "${agent_dns_port}"

# Delete out chain 
iptables -t nat -D OUTPUT -j "${chain_name}"

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