#!/bin/bash

# check root 
if [[ $(id -u) -ne 0 ]]
then
	echo -e "This script requires root privilages!"
	exit 1
fi

# validate arguments
if [[ $# -ne 1 || ! $1 =~ ^150.254.32.[1-2]?[0-9]?[0-9]$ ]]
then
	echo -e "Redirects all DNS queries sent to DNS servers outside 150.254.0.0/16 to the given IP address 150.254.32.XXX\n  Usage:\n  $0 <150.254.32.XXX>"
	exit 2
fi

# clean up old mess
iptables -t mangle -D OUTPUT -p udp --dport 53 ! -d 150.254.0.0/16 -j MARK --set-mark 0xdeadbeef 2>/dev/null
iptables -t mangle -D OUTPUT -p tcp --dport 53 ! -d 150.254.0.0/16 -j MARK --set-mark 0xdeadbeef 2>/dev/null
ip rule del fwmark 0xdeadbeef lookup 10 2>/dev/null
ip route flush table 10

# add default route to table 10 (or die) 
ip route add table 10 default via $1
if (( $? ))
then
	echo -e "Address $1 is incorrect"
	exit 3
fi
# look up table 10 on packages marked as 0xdeadbeef
ip rule add fwmark 0xdeadbeef lookup 10

# mark normal DNS queries with 0xdeadbeef
iptables -t mangle -A OUTPUT -p udp --dport 53 ! -d 150.254.0.0/16 -j MARK --set-mark 0xdeadbeef
# mark axfr DNS queries with 0xdeadbeef
iptables -t mangle -A OUTPUT -p tcp --dport 53 ! -d 150.254.0.0/16 -j MARK --set-mark 0xdeadbeef

# test if a sample query works
if [[ "$(dig +short -x 1.1.1.1 @1.1.1.1)" == "one.one.one.one." ]]
then
	echo "All fine"
else
	echo "Failed"
fi
