#!/bin/bash
#
#	This script is used to set up iptables rules on instructor to redirect
#	all smtp traffic from desktopX to instructor back to serverX.  This
#	will allow learners to set up their machines to do the following:
#
#	serverX - intranet mail server (can receive all e-mail for "example.com")
#	desktopX - outbound relay host (handles all outgoing e-mail for ex.com)
#
#	Since DNS MX record for example.com points to instructor.example.com,
#	desktopX will try to deliver all mail to that host. This approach allows
#	each of the learners to set up mail services for example.com without
#	having to do any complicated DNS magic.
#

to_email_port='-p tcp --dport 25'
instructor=192.168.0.254

if [ "$1" = '--reverse' ]
then
	iptables_op=-D
elif [ $# == 0 ]
then
	iptables_op=-I
else
	echo 'Usage: gls-email-iptables [--reverse]'
	exit 1
fi

# count down from 20 by 1
for i in $(seq 20 -1 1)
do
	desktopX=192.168.0.$i
	serverX=192.168.0.$((100+i))
	iptables -t nat ${iptables_op} PREROUTING -s ${desktopX} ${to_email_port} \
		 -j DNAT --to-destination ${serverX}
done
iptables -t nat ${iptables_op} POSTROUTING -s 192.168.0.0/24 ${to_email_port} \
	 -j SNAT --to-source ${instructor}
