#!/bin/bash -e

trap "" TSTP
trap "" HUP
trap "" INT

export PATH="/bin:/sbin:/usr/sbin:/usr/bin"

readonly OSX_VERSION="$(sw_vers | grep 'ProductVersion:' | grep -o '10\.[0-9]*')"
readonly DEFAULT_DOMAIN_NAME="openvpn"

SCRIPT_LOG_FILE="/opt/local/var/log/openvpn2/client.log"
WATCHER_PLIST="/Library/LaunchDaemons/net.openvpn.watcher.plist"

# TODO Run some tests to make these dynamic
MONITOR_NETWORK="true"
RESTORE_ON_RESET="true"
IS_TAP="false"
bRouteGatewayIsDhcp="false"

# @param String message - The message to log
readonly LOG_MESSAGE_COMMAND=$(basename "${0}")
logMessage()
{
	echo "$(date '+%a %b %e %T %Y') *OpenVPN $LOG_MESSAGE_COMMAND: "${@} >> "${SCRIPT_LOG_FILE}"
}

# @param String string - Content to trim
trim()
{
	echo ${@}
}

# @param String[] dnsServers - The name servers to use
# @param String domainName - The domain name to use
# @param \optional String[] winsServers - The WINS servers to use
setDnsServersAndDomainName()
{
	OPENVPN_SERVER_ADDRESSES=("${!1}")
	OPENVPN_SEARCH_DOMAIN=$2
	OPENVPN_WINS=("${!3}")
	
	set +e # "grep" will return error status (1) if no matches are found, so don't fail on individual errors
	
	PRIMARY_SERVICE_ID=$( (scutil | grep PrimaryService | sed -e 's/.*PrimaryService : //')<<- EOF
		open
		show State:/Network/Global/IPv4
		quit
EOF )
	
	PRIMARY_SERVICE_STATIC_DNS="$( (scutil | sed -e 's/^[[:space:]]*[[:digit:]]* : //g' | tr '\n' ' ')<<- EOF
		open
		show Setup:/Network/Service/${PRIMARY_SERVICE_ID}/DNS
		quit
EOF )"
	if echo "${PRIMARY_SERVICE_STATIC_DNS}" | grep -q "ServerAddresses" ; then
		readonly PRIMARY_SERVICE_STATIC_SERVER_ADDRESSES="$(trim "$( echo "${PRIMARY_SERVICE_STATIC_DNS}" | sed -e 's/^.*ServerAddresses[^{]*{[[:space:]]*\([^}]*\)[[:space:]]*}.*$/\1/g' )")"
	fi
	if echo "${PRIMARY_SERVICE_STATIC_DNS}" | grep -q "SearchDomains" ; then
		readonly PRIMARY_SERVICE_STATIC_SEARCH_DOMAINS="$(trim "$( echo "${PRIMARY_SERVICE_STATIC_DNS}" | sed -e 's/^.*SearchDomains[^{]*{[[:space:]]*\([^}]*\)[[:space:]]*}.*$/\1/g' )")"
	fi
	
	PRIMARY_SERVICE_STATIC_SMB="$( (scutil | sed -e 's/^[[:space:]]*[[:digit:]]* : //g' | tr '\n' ' ')<<- EOF
		open
		show Setup:/Network/Service/${PRIMARY_SERVICE_ID}/SMB
		quit
EOF )"
	if echo "${PRIMARY_SERVICE_STATIC_SMB}" | grep -q "WINSAddresses" ; then
		readonly PRIMARY_SERVICE_STATIC_WINS_ADDRESSES="$(trim "$( echo "${PRIMARY_SERVICE_STATIC_SMB}" | sed -e 's/^.*WINSAddresses[^{]*{[[:space:]]*\([^}]*\)[[:space:]]*}.*$/\1/g' )")"
	fi
	if [ -n "${PRIMARY_SERVICE_STATIC_SMB}" ] ; then
		readonly PRIMARY_SERVICE_STATIC_WORKGROUP="$(trim "$( echo "${PRIMARY_SERVICE_STATIC_SMB}" | sed -e 's/^.*Workgroup : \([^[:space:]]*\).*$/\1/g' )")"
	fi
	if echo "${PRIMARY_SERVICE_STATIC_SMB}" | grep -q "NetBIOSName" ; then
		readonly PRIMARY_SERVICE_STATIC_NETBIOS_NAME="$(trim "$( echo "${PRIMARY_SERVICE_STATIC_SMB}" | sed -e 's/^.*NetBIOSName : \([^[:space:]]*\).*$/\1/g' )")"
	fi

	if [ ${#OPENVPN_SERVER_ADDRESSES[*]} -eq 0 ] ; then
		DYNAMIC_SERVER_ADDRESSES="false"
		ALL_SERVER_ADDRESSES="${PRIMARY_SERVICE_STATIC_SERVER_ADDRESSES}"
	elif [ -n "${PRIMARY_SERVICE_STATIC_SERVER_ADDRESSES}" ] ; then
		case "${OSX_VERSION}" in
			10.6 | 10.7 )
				# Do nothing - in 10.6 we don't aggregate our configurations, apparently
				DYNAMIC_SERVER_ADDRESSES="false"
				ALL_SERVER_ADDRESSES="${PRIMARY_SERVICE_STATIC_SERVER_ADDRESSES}"
				;;
			10.4 | 10.5 )
				DYNAMIC_SERVER_ADDRESSES="true"
				# We need to remove duplicate DNS entries, so that our reference list matches MacOSX's
				SDNS="$(echo "${PRIMARY_SERVICE_STATIC_SERVER_ADDRESSES}" | tr ' ' '\n')"
				(( i=0 ))
				for n in "${OPENVPN_SERVER_ADDRESSES[@]}" ; do
					if echo "${SDNS}" | grep -q "${n}" ; then
						unset OPENVPN_SERVER_ADDRESSES[${i}]
					fi
					(( i++ ))
				done
				if [ ${#OPENVPN_SERVER_ADDRESSES[*]} -gt 0 ] ; then
					ALL_SERVER_ADDRESSES="$(trim "${PRIMARY_SERVICE_STATIC_SERVER_ADDRESSES}" "${OPENVPN_SERVER_ADDRESSES[*]}")"
				else
					DYNAMIC_SERVER_ADDRESSES="false"
					ALL_SERVER_ADDRESSES="${PRIMARY_SERVICE_STATIC_SERVER_ADDRESSES}"
				fi
				;;
		esac
	else
		DYNAMIC_SERVER_ADDRESSES="true"
		ALL_SERVER_ADDRESSES="$(trim "${OPENVPN_SERVER_ADDRESSES[*]}")"
	fi
	readonly DYNAMIC_SERVER_ADDRESSES ALL_SERVER_ADDRESSES

	if [ ${#OPENVPN_WINS[*]} -eq 0 ] ; then
		DYNAMIC_WINS_ADDRESSES="false"
		ALL_WINS_ADDRESSES="${PRIMARY_SERVICE_STATIC_WINS_ADDRESSES}"
	elif [ -n "${PRIMARY_SERVICE_STATIC_WINS_ADDRESSES}" ] ; then
		case "${OSX_VERSION}" in
			10.6 | 10.7 )
				# Do nothing - in 10.6 we don't aggregate our configurations, apparently
				DYNAMIC_WINS_ADDRESSES="false"
				ALL_WINS_ADDRESSES="${PRIMARY_SERVICE_STATIC_WINS_ADDRESSES}"
				;;
			10.4 | 10.5 )
				DYNAMIC_WINS_ADDRESSES="true"
				# We need to remove duplicate WINS entries, so that our reference list matches MacOSX's
				SWINS="$(echo "${PRIMARY_SERVICE_STATIC_WINS_ADDRESSES}" | tr ' ' '\n')"
				(( i=0 ))
				for n in "${OPENVPN_WINS[@]}" ; do
					if echo "${SWINS}" | grep -q "${n}" ; then
						unset OPENVPN_WINS[${i}]
					fi
					(( i++ ))
				done
				if [ ${#OPENVPN_WINS[*]} -gt 0 ] ; then
					ALL_WINS_ADDRESSES="$(trim "${PRIMARY_SERVICE_STATIC_WINS_ADDRESSES}" "${OPENVPN_WINS[*]}")"
				else
					DYNAMIC_WINS_ADDRESSES="false"
					ALL_WINS_ADDRESSES="${PRIMARY_SERVICE_STATIC_WINS_ADDRESSES}"
				fi
				;;
		esac
	else
		DYNAMIC_WINS_ADDRESSES="true"
		ALL_WINS_ADDRESSES="$(trim "${OPENVPN_WINS[*]}")"
	fi
	readonly DYNAMIC_WINS_ADDRESSES ALL_WINS_ADDRESSES

	# We double-check that our search domain isn't already on the list
	SEARCH_DOMAIN=${OPENVPN_SEARCH_DOMAIN}
	case "${OSX_VERSION}" in
		10.6 | 10.7 )
			# Do nothing - in 10.6 we don't aggregate our configurations, apparently
			if [ -n "${PRIMARY_SERVICE_STATIC_SEARCH_DOMAINS}" ] ; then
				ALL_SEARCH_DOMAINS="${PRIMARY_SERVICE_STATIC_SEARCH_DOMAINS}"
				SEARCH_DOMAIN=""
			else
				ALL_SEARCH_DOMAINS="${SEARCH_DOMAIN}"
			fi
			;;
		10.4 | 10.5 )
			if echo "${PRIMARY_SERVICE_STATIC_SEARCH_DOMAINS}" | tr ' ' '\n' | grep -q "${OPENVPN_SEARCH_DOMAIN}" ; then
				SEARCH_DOMAIN=""
			fi
			if [ -z "${SEARCH_DOMAIN}" ] ; then
				ALL_SEARCH_DOMAINS="${PRIMARY_SERVICE_STATIC_SEARCH_DOMAINS}"
			else
				ALL_SEARCH_DOMAINS="$(trim "${PRIMARY_SERVICE_STATIC_SEARCH_DOMAINS}" "${SEARCH_DOMAIN}")"
			fi
			;;
	esac
	readonly SEARCH_DOMAIN ALL_SEARCH_DOMAINS

	# DEBUG
	#logMessage "DYNAMIC_SERVER_ADDRESSES: ${DYNAMIC_SERVER_ADDRESSES}"
	#logMessage "DYNAMIC_WINS_ADDRESSES: ${DYNAMIC_WINS_ADDRESSES}"
	#logMessage "OPENVPN_SEARCH_DOMAIN: ${OPENVPN_SEARCH_DOMAIN}"
	#logMessage "SEARCH_DOMAIN: ${SEARCH_DOMAIN}"
	#logMessage "PRIMARY_SERVICE_STATIC_WORKGROUP: ${PRIMARY_SERVICE_STATIC_WORKGROUP}"
	#logMessage "PRIMARY_SERVICE_STATIC_NETBIOS_NAME: ${PRIMARY_SERVICE_STATIC_NETBIOS_NAME}"
	#logMessage "ALL_SERVER_ADDRESSES: ${ALL_SERVER_ADDRESSES}"
	#logMessage "ALL_SEARCH_DOMAINS: ${ALL_SEARCH_DOMAINS}"
	#logMessage "ALL_WINS_ADDRESSES: ${ALL_WINS_ADDRESSES}"

	if ! ${DYNAMIC_SERVER_ADDRESSES} ; then
		NO_SERVER_ADDRESSES="#"
	fi
	if ! ${DYNAMIC_WINS_ADDRESSES} ; then
		NO_WINS_ADDRESSES="#"
	fi
	if [ -z "${SEARCH_DOMAIN}" ] ; then
		NO_SEARCH_DOMAIN="#"
	fi
	if [ -z "${PRIMARY_SERVICE_STATIC_WORKGROUP}" ] ; then
		NO_WORKGROUP="#"
	fi
	if [ -z "${PRIMARY_SERVICE_STATIC_NETBIOS_NAME}" ] ; then
		NO_NETBIOS_NAME="#"
	fi
	if [ -z "${ALL_SERVER_ADDRESSES}" ] ; then
		NO_AGGREGATE_SERVER_ADDRESSES="#"
	fi
	if [ -z "${ALL_SEARCH_DOMAINS}" ] ; then
		NO_AGGREGATE_SEARCH_DOMAINS="#"
	fi
	if [ -z "${ALL_WINS_ADDRESSES}" ] ; then
		NO_AGGREGATE_WINS_ADDRESSES="#"
	fi
	
	# Now, do the aggregation:
	#   - Save the openvpn process ID and the Network Primary Service ID, and logfile path
	#   - Then save old and new DNS and WINS settings
	#   - PPID is a bash-script variable that contains the process ID of the parent of the process running the script (i.e., OpenVPN's process ID)
	#   - config is an environmental variable set to the configuration path by OpenVPN prior to running this up script
	logMessage "Up to two 'No such key' warnings are normal and may be ignored"
	
	# If DNS is manually set, it overrides the DHCP setting, which isn't reflected in 'State:/Network/Service/${PRIMARY_SERVICE_ID}/DNS'
	if echo "${PRIMARY_SERVICE_STATIC_DNS}" | grep -q "ServerAddresses" ; then
		CORRECT_OLD_DNS_KEY="Setup:"
	else
		CORRECT_OLD_DNS_KEY="State:"
	fi
	
	# If WINS is manually set, it overrides the DHCP setting, which isn't reflected in 'State:/Network/Service/${PRIMARY_SERVICE_ID}/DNS'
	if echo "${PRIMARY_SERVICE_STATIC_SMB}" | grep -q "WINSAddresses" ; then
		CORRECT_OLD_WINS_KEY="Setup:"
	else
		CORRECT_OLD_WINS_KEY="State:"
	fi
	
	set -e # We instruct bash that it CAN again fail on errors

	scutil <<- EOF
		open
		d.init

		d.add PID                   # ${PPID}
		d.add Service               ${PRIMARY_SERVICE_ID}
                d.add WatcherPlist          "${WATCHER_PLIST}"
                d.add ScriptLogFile         "${SCRIPT_LOG_FILE}"
                d.add MonitorNetwork        "${MONITOR_NETWORK}"
                d.add RestoreOnReset        "${RESTORE_ON_RESET}"
                d.add IsTapInterface        "${IS_TAP}"
                d.add RouteGatewayIsDhcp    "${bRouteGatewayIsDhcp}"
		set State:/Network/OpenVPN
		
		# First, back up the device's current DNS and WINS configurations
		# Indicate 'no such key' by a dictionary with a single entry: "NoSuchKey : true"
		d.init
		d.add NoSuchKey true
		get ${CORRECT_OLD_DNS_KEY}/Network/Service/${PRIMARY_SERVICE_ID}/DNS
		set State:/Network/OpenVPN/OldDNS
		
		d.init
		d.add NoSuchKey true
		get ${CORRECT_OLD_WINS_KEY}/Network/Service/${PRIMARY_SERVICE_ID}/SMB
		set State:/Network/OpenVPN/OldSMB
		
		# Second, initialize the new DNS map
		d.init
		${NO_SERVER_ADDRESSES}d.add ServerAddresses * ${OPENVPN_SERVER_ADDRESSES[*]}
		${NO_SEARCH_DOMAIN}d.add SearchDomains * ${SEARCH_DOMAIN}
		d.add DomainName ${OPENVPN_SEARCH_DOMAIN}
		set State:/Network/Service/${PRIMARY_SERVICE_ID}/DNS
		
		# Third, initialize the WINS map
		d.init
		${NO_NETBIOS_NAME}d.add NetBIOSName ${PRIMARY_SERVICE_STATIC_NETBIOS_NAME}
		${NO_WINS_ADDRESSES}d.add WINSAddresses * ${OPENVPN_WINS[*]}
		${NO_WORKGROUP}d.add Workgroup ${PRIMARY_SERVICE_STATIC_WORKGROUP}
		set State:/Network/Service/${PRIMARY_SERVICE_ID}/SMB
		
		# Now, initialize the maps that will be compared against the system-generated map
		# which means that we will have to aggregate configurations of statically-configured
		# nameservers, and statically-configured search domains
		d.init
		${NO_AGGREGATE_SERVER_ADDRESSES}d.add ServerAddresses * ${ALL_SERVER_ADDRESSES}
		${NO_AGGREGATE_SEARCH_DOMAINS}d.add SearchDomains * ${ALL_SEARCH_DOMAINS}
		d.add DomainName ${OPENVPN_SEARCH_DOMAIN}
		set State:/Network/OpenVPN/DNS
		
		d.init
		${NO_NETBIOS_NAME}d.add NetBIOSName ${PRIMARY_SERVICE_STATIC_NETBIOS_NAME}
		${NO_AGGREGATE_WINS_ADDRESSES}d.add WINSAddresses * ${ALL_WINS_ADDRESSES}
		${NO_WORKGROUP}d.add Workgroup ${PRIMARY_SERVICE_STATIC_WORKGROUP}
		set State:/Network/OpenVPN/SMB
		
		# We're done
		quit
EOF
	
	logMessage "Saved the DNS and WINS configurations for later use"

        if ${MONITOR_NETWORK} ; then
		sleep 2
                launchctl load "${WATCHER_PLIST}"
                logMessage "Set up to monitor system configuration with leasewatch"
        fi
}

configureDhcpDns()
{
	# whilst ipconfig will have created the neccessary Network Service keys, the DNS
	# settings won't actually be used by OS X unless the SupplementalMatchDomains key
	# is added
	# ref. <http://lists.apple.com/archives/Macnetworkprog/2005/Jun/msg00011.html>
	# - is there a way to extract the domains from the SC dictionary and re-insert
	#   as SupplementalMatchDomains? i.e. not requiring the ipconfig domain_name call?
	
	# - wait until we get a lease before extracting the DNS domain name and merging into SC
	# - despite it's name, ipconfig waitall doesn't (but maybe one day it will :-)
	ipconfig waitall
	
	unset test_domain_name
	unset test_name_server
	
	set +e # We instruct bash NOT to exit on individual command errors, because if we need to wait longer these commands will fail
	
	# usually takes at least a few seconds to get a DHCP lease
	sleep 3
	n=0
	while [ -z "$test_domain_name" -a -z "$test_name_server" -a $n -lt 5 ]
	do
		logMessage "Sleeping for $n seconds to wait for DHCP to finish setup."
		sleep $n
		n=`expr $n + 1`
		
		if [ -z "$test_domain_name" ]; then
			test_domain_name=`ipconfig getoption $dev domain_name 2>/dev/null`
		fi
		
		if [ -z "$test_name_server" ]; then
			test_name_server=`ipconfig getoption $dev domain_name_server 2>/dev/null`
		fi
	done
	
	sGetPacketOutput=`ipconfig getpacket $dev`
	
	set -e # We instruct bash that it CAN again fail on individual errors
	
	#echo "`date` test_domain_name = $test_domain_name, test_name_server = $test_name_server, sGetPacketOutput = $sGetPacketOutput"
	
	unset aNameServers
	unset aWinsServers
	
	nNameServerIndex=1
	nWinsServerIndex=1
	
	if [ "$sGetPacketOutput" ]; then
		sGetPacketOutput_FirstLine=`echo "$sGetPacketOutput"|head -n 1`
		#echo $sGetPacketOutput_FirstLine
		
		if [ "$sGetPacketOutput_FirstLine" == "op = BOOTREPLY" ]; then
			set +e # "grep" will return error status (1) if no matches are found, so don't fail on individual errors
			
			for tNameServer in `echo "$sGetPacketOutput"|grep "domain_name_server"|grep -Eo "\{([0-9\.]+)(, [0-9\.]+)*\}"|grep -Eo "([0-9\.]+)"`; do
				aNameServers[nNameServerIndex-1]="$(trim "$tNameServer")"
				let nNameServerIndex++
			done
			
			for tWINSServer in `echo "$sGetPacketOutput"|grep "nb_over_tcpip_name_server"|grep -Eo "\{([0-9\.]+)(, [0-9\.]+)*\}"|grep -Eo "([0-9\.]+)"`; do
				aWinsServers[nWinsServerIndex-1]="$(trim "$tWINSServer")"
				let nWinsServerIndex++
			done
			
			sDomainName=`echo "$sGetPacketOutput"|grep "domain_name "|grep -Eo ": [-A-Za-z0-9\-\.]+"|grep -Eo "[-A-Za-z0-9\-\.]+"`
			sDomainName="$(trim "$sDomainName")"
			
			if [ ${#aNameServers[*]} -gt 0 -a "$sDomainName" ]; then
				logMessage "Retrieved name server(s) [ ${aNameServers[@]} ], domain name [ $sDomainName ], and WINS server(s) [ ${aWinsServers[@]} ]"
				setDnsServersAndDomainName aNameServers[@] "$sDomainName" aWinsServers[@]
				return 0
			elif [ ${#aNameServers[*]} -gt 0 ]; then
				logMessage "Retrieved name server(s) [ ${aNameServers[@]} ] and WINS server(s) [ ${aWinsServers[@]} ] and using default domain name [ $DEFAULT_DOMAIN_NAME ]"
				setDnsServersAndDomainName aNameServers[@] "$DEFAULT_DOMAIN_NAME" aWinsServers[@]
				return 0
			else
				# Should we return 1 here and indicate an error, or attempt the old method?
				logMessage "No useful information extracted from DHCP/BOOTP packet. Attempting legacy configuration."
			fi
			
			set -e # We instruct bash that it CAN again fail on errors
		else
			# Should we return 1 here and indicate an error, or attempt the old method?
			logMessage "No DHCP/BOOTP packet found on interface. Attempting legacy configuration."
		fi
	fi
	
	unset sDomainName
	unset sNameServer
	unset aNameServers
	
	sDomainName=`ipconfig getoption $dev domain_name 2>/dev/null`
	sNameServer=`ipconfig getoption $dev domain_name_server 2>/dev/null`
	
	sDomainName="$(trim "$sDomainName")"
	sNameServer="$(trim "$sNameServer")"
	
	declare -a aWinsServers=( ) # Declare empty WINS array to avoid any useless error messages
	
	if [ "$sDomainName" -a "$sNameServer" ]; then
		aNameServers[0]=$sNameServer
		logMessage "Retrieved name server [ $sNameServer ], domain name [ $sDomainName ], and no WINS servers"
		setDnsServersAndDomainName aNameServers[@] "$sDomainName" aWinsServers[@]
	elif [ "$sNameServer" ]; then
		aNameServers[0]=$sNameServer
		logMessage "Retrieved name server [ $sNameServer ] and no WINS servers, and using default domain name [ $DEFAULT_DOMAIN_NAME ]"
		setDnsServersAndDomainName aNameServers[@] "$DEFAULT_DOMAIN_NAME" aWinsServers[@]
	elif [ "$sDomainName" ]; then
		logMessage "WARNING: Retrieved domain name [ $sDomainName ] but no name servers from OpenVPN (DHCP), which is not sufficient to make network/DNS configuration changes."
	else
		logMessage "WARNING: No DNS information recieved from OpenVPN (DHCP), so no network/DNS configuration changes need to be made."
	fi
	
	return 0
}

configureOpenVpnDns()
{
	unset vForOptions
	unset vOptions
	unset aNameServers
	unset aWinsServers
	
	nOptionIndex=1
	nNameServerIndex=1
	nWinsServerIndex=1

	while vForOptions=foreign_option_$nOptionIndex; [ -n "${!vForOptions}" ]; do
		vOptions[nOptionIndex-1]=${!vForOptions}
		case ${vOptions[nOptionIndex-1]} in
			*DOMAIN* )
				sDomainName="$(trim "${vOptions[nOptionIndex-1]//dhcp-option DOMAIN /}")"
				;;
			*DNS*    )
				aNameServers[nNameServerIndex-1]="$(trim "${vOptions[nOptionIndex-1]//dhcp-option DNS /}")"
				let nNameServerIndex++
				;;
			*WINS*   )
				aWinsServers[nWinsServerIndex-1]="$(trim "${vOptions[nOptionIndex-1]//dhcp-option WINS /}")"
				let nWinsServerIndex++
				;;
		esac
		let nOptionIndex++
	done
	
	if [ ${#aNameServers[*]} -gt 0 -a "$sDomainName" ]; then
		logMessage "Retrieved name server(s) [ ${aNameServers[@]} ], domain name [ $sDomainName ], and WINS server(s) [ ${aWinsServers[@]} ]"
		setDnsServersAndDomainName aNameServers[@] "$sDomainName" aWinsServers[@]
	elif [ ${#aNameServers[*]} -gt 0 ]; then
		logMessage "Retrieved name server(s) [ ${aNameServers[@]} ] and WINS server(s) [ ${aWinsServers[@]} ] and using default domain name [ $DEFAULT_DOMAIN_NAME ]"
		setDnsServersAndDomainName aNameServers[@] "$DEFAULT_DOMAIN_NAME" aWinsServers[@]
	else
		# Should we maybe just return 1 here to indicate an error? Does this mean that something bad has happened?
		logMessage "No DNS information recieved from OpenVPN, so no network configuration changes need to be made."
	fi
	
	return 0
}

# We sleep here to allow time for OS X to process network settings
sleep 2

EXIT_CODE=0

if ${IS_TAP} ; then
	# Still need to do: Look for route-gateway dhcp (TAP isn't always DHCP)
	bRouteGatewayIsDhcp="false"
	if [ -z "${route_vpn_gateway}" -o "$route_vpn_gateway" == "dhcp" -o "$route_vpn_gateway" == "DHCP" ]; then
		bRouteGatewayIsDhcp="true"
	fi
	
	if [ "$bRouteGatewayIsDhcp" == "true" ]; then
		if [ -z "$dev" ]; then
			logMessage "Cannot configure TAP interface for DHCP without \$dev being defined. Exiting."
			exit 1
		fi
		
		ipconfig set "$dev" DHCP
		
		configureDhcpDns &
	elif [ "$foreign_option_1" == "" ]; then
		logMessage "No network configuration changes need to be made."
	else
		configureOpenVpnDns
		EXIT_CODE=$?
	fi
else
	if [ "$foreign_option_1" == "" ]; then
		logMessage "No network configuration changes need to be made."
	else
		configureOpenVpnDns
		EXIT_CODE=$?
	fi
fi

exit $EXIT_CODE
