#!/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]$ && ! $1 =~ ^10.[1-2]?[0-9]?[0-9].[1-2]?[0-9]?[0-9].[1-2]?[0-9]?[0-9]$ ) ]]
then
	echo -e "Redirects all DNS queries sent to (other than university's) DNS servers to the given IP address 150.254.32.X or 10.X.X.X\n  Usage:\n  $0 <150.254.32.XX|10.X.X.X>"
	exit 2
fi

# clean up old mess
iptables -t mangle -F &>/dev/null
ip -4 rule del fwmark 0xdeadbeef lookup 10 &>/dev/null
ip -4 route flush table 10 &>/dev/null
ip6tables -t mangle -F &>/dev/null
ip -6 rule del fwmark 0xdeadbeef lookup 10 &>/dev/null
ip -6 route flush table 10 &>/dev/null

# add default route to table 10 (or die) 
ip -4 route add table 10 default via $1
if (( $? ))
then
	echo -e "Address $1 is incorrect"
	exit 3
fi
ip -6 route add table 10 default via fe80::53 dev br0

# look up table 10 on packages marked as 0xdeadbeef
ip -4 rule add fwmark 0xdeadbeef lookup 10
ip -6 rule add fwmark 0xdeadbeef lookup 10

for P in udp tcp
do
	# mark all DNS queries with 0xdeadbeef
	iptables  -t mangle -A OUTPUT -p $P --dport 53                       -j MARK --set-mark 0xdeadbeef
	ip6tables -t mangle -A OUTPUT -p $P --dport 53                       -j MARK --set-mark 0xdeadbeef
	
	# clear mark on PUT DNS servers + lab computers
	iptables  -t mangle -A OUTPUT -p $P --dport 53 -d 150.254.5.4        -j MARK --set-mark 0
	iptables  -t mangle -A OUTPUT -p $P --dport 53 -d 150.254.5.11       -j MARK --set-mark 0
	iptables  -t mangle -A OUTPUT -p $P --dport 53 -d 150.254.30.30      -j MARK --set-mark 0
	iptables  -t mangle -A OUTPUT -p $P --dport 53 -d 150.254.32.0/24    -j MARK --set-mark 0
	iptables  -t mangle -A OUTPUT -p $P --dport 53 -d 192.168.0.0/16     -j MARK --set-mark 0
	ip6tables -t mangle -A OUTPUT -p $P --dport 53 -d 2001:808:201::5:4  -j MARK --set-mark 0
	ip6tables -t mangle -A OUTPUT -p $P --dport 53 -d 2001:808:201::5:11 -j MARK --set-mark 0
done

# 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
