#!/bin/sh

# Test if a route exists to the VPN server
route_exist=`ip route show 192.41.170.56`
if [ "XX$route_exist" != "XX" ]; then
    logger -p user.info -t openvpn.up Deleting existing route to VPN server
    ip route del 192.41.170.56
fi

# Set a route to the VPN server using the default route, as resolved by
# the existing routing table
ip route add to `ip route get 192.41.170.56|cut -d' ' -f 1-3|sed '/^ *$/d'`
logger -p user.info -t openvpn.up Route to VPN server has been added

# DHCP address can only be obtained after the VPN connection had fully
# initialized. Run DHCP in a separate and detached process.
(while :
       # loop indefinitely until we get a dynamic IP
 do
     dhclient $1
     ret=$?
     if [ $ret -eq 0 ] ; then
	 # dhclient will sometime resolve to some private IP coming from
	 # dunno where. If it gets a response from CSIM DHCP server, it
	 # it will create a route to CSIM through the tap interface.
	 # If that route is not created, it means dhclient has failed
	 # and we must try again.
	 route_exist=`ip route show 192.41.170.0/24`
	 if [ "XX$route_exist" != "XX" ]; then
	     # We have a route to CSIM
	     logger -p user.info -t openvpn.up Got dynamic IP with dhclient $1
	     # Add a route to AIT
	     ip route add to 203.159.0.0/18 via 192.41.170.23
	     exit
	 else
	     # We have a false answer to DHCP
	     logger -p user.info -t openvpn.up Got an invalid IP with dhclient $1
         fi
     fi
     logger -p user.info -t openvpn.up Could not get dynamic IP yet dhclient $1: $ret
 done
) &

# Return to OpenVPN to finish the connection
exit


