#!/bin/bash
#
# by: Joshua M. Hoffman & George Hacker
#
# Setup the network routing lab
# this script is to be installed and run on desktopX.example.com
# output is logged to syslog

# Set environment and declare global variables
. /usr/local/lib/labtool.shlib
trap on_exit EXIT

DEBUG=false
PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/local/sbin
userInput="no"
set -o pipefail

# Check to make sure we are running as root
check_root

# Check to make sure we are running on the correct host
check_host "desktop"

# This script should not be executed multiple times without cleanup
if [ -f /root/iptables-active  ] ; then
   echo 'Error: lab-setup-routing has already been executed'
   echo 'Cleanup before executing this utility again.'
   exit 1
fi

# Prompt the user before we make any changes to the system
cat <<EOL

*** NOTICE ***
This script will reset vserver to setup the exercise.
EOL
confirm
echo
echo -n "Setting up, one moment please... "

# Back up existing iptables rules
(iptables-save > /root/iptables-active 2>&1 | log) || exit
([ -f /etc/sysconfig/iptables ] && cp -a /etc/sysconfig/iptables /root/iptables-persist 2>&1 | log)

# Configure vserver to use the private network
(gls-vserver-network2 --private 2>&1 | log) || exit

# Clear iptables rules (this step must come after network adjustment
# because libvirt adds iptables rules for the private network bridge).
iptables -t nat -F
iptables -t filter -F
(service iptables save 2>&1 | log) || exit

# Reset vserver
(/usr/local/sbin/lab-resetvm 2>&1 | log) || exit

echo 'done!'

exit 0
