#!/bin/bash
#
# Stage 2 boot script
# Called when the drivers are loaded and the CD is mounted
#
# TJD June 2002
#

# Machine and port of the SOAP service
BOOTSERVER=`cat /usr/bootme/BOOTSERVER`
BOOTPORT=`cat /usr/bootme/BOOTPORT`
# Fallback IP address in case DNS doesn't provide
BOOTSERVER_IP=`cat /usr/bootme/BOOTSERVER_IP`


# Configure the network
echo ""
IFC=`ifconfig eth0`
if [ $? -ne 0 ] ; then 
    echo "Can't find eth0: try loading network drivers by hand."
    exit 1
fi
if (echo "$IFC" | grep -q '^[[:space:]]*UP ' ) ; then
    echo "NIC eth0 is already configured."
else
    echo "Trying DHCP for eth0:"
    if (dhcpcd -t 60 eth0) ; then
#    if (ifconfig eth0 128.232.32.70 broadcast 128.232.32.255 netmask 255.255.255.0 && route add -net default gw 128.232.32.1) ; then
	echo "DHCP succeeded"
    else
	echo "DHCP failed"
    fi
fi

# Report the network
echo ""
ifconfig eth0
netstat -rn
echo ""


# Turn on the iptables
echo "Setting up iptables"
iptables -F INPUT
iptables -F OUTPUT
iptables -F FORWARD
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP
# Necessary traffic
iptables -A INPUT -p icmp -j ACCEPT
iptables -A OUTPUT -p icmp -j ACCEPT
iptables -A INPUT -p udp --sport bootps --dport bootpc -j ACCEPT
iptables -A OUTPUT -p udp --sport bootpc --dport bootps -j ACCEPT
iptables -A INPUT -p udp --sport 53 -j ACCEPT
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
# Outbound TCP
iptables -A INPUT -p tcp ! --syn -j ACCEPT
iptables -A OUTPUT -p tcp -j ACCEPT


echo ""

# Find out the IP addresses of the bootserver
# N.B. This will not work with CNAMES
echo "Finding the bootserver"
IPS=`dig $BOOTSERVER A | awk \
  "/^${BOOTSERVER}/"' { if ($4 == "A") print $5 " " }'`
echo "${BOOTSERVER}: ${IPS}(${BOOTSERVER_IP})"
IPS="${IPS}${BOOTSERVER_IP}"
echo ""

# Fetchez!
for IP in $IPS; do
    SOAPURI="https://${BOOTSERVER}:${BOOTPORT}/BootMe/";
    SOAPPROXY="https://${IP}:${BOOTPORT}/"
    echo "SOAP: $SOAPURI ($IP)"
    rm -f /tmp/bootscript
    /usr/bootme/soapclient.pl $SOAPURI $SOAPPROXY
    if [ $? -ne 0 -o \! -x /tmp/bootscript ] ; then
    	echo "SOAP: request failed."
    else
    	echo "SOAP: request succeeded, got bootscript."
    	echo "Handing control to /tmp/bootscript"
    	/tmp/bootscript
    	echo
    	echo "/tmp/bootscript has returned."
    fi
done
echo "Out of server IP addresses: boot failed."

#
# EOF
#