#!/bin/bash -e

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

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

readonly LOG_MESSAGE_COMMAND=$(basename "${0}")

# Quick check - is the configuration there?
if ! scutil -w State:/Network/OpenVPN &>/dev/null -t 1 ; then
	# Configuration isn't there, so we forget it
	echo "$(date '+%a %b %e %T %Y') *OpenVPN $LOG_MESSAGE_COMMAND: WARNING: No existing OpenVPN DNS configuration found; not tearing down anything; exiting."
	exit 0
fi

# Get info saved by the up script
OPENVPN_CONFIG="$(/usr/sbin/scutil <<-EOF
	open
	show State:/Network/OpenVPN
	quit
EOF)"

MONITOR_NETWORK="$(echo "${OPENVPN_CONFIG}" | grep -i '^[[:space:]]*MonitorNetwork :' | sed -e 's/^.*: //g')"
WATCHER_PLIST="$(echo "${OPENVPN_CONFIG}" | grep -i '^[[:space:]]*WatcherPlist :' | sed -e 's/^.*: //g')"
PRIMARY_SERVICE_ID="$(echo "${OPENVPN_CONFIG}" | grep -i '^[[:space:]]*Service :' | sed -e 's/^.*: //g')"
SCRIPT_LOG_FILE="$(echo "${OPENVPN_CONFIG}" | grep -i '^[[:space:]]*ScriptLogFile :' | sed -e 's/^.*: //g')"
IS_TAP="$(echo "${OPENVPN_CONFIG}" | grep -i '^[[:space:]]*IsTapInterface :' | sed -e 's/^.*: //g')"
bRouteGatewayIsDhcp="$(echo "${OPENVPN_CONFIG}" | grep -i '^[[:space:]]*RouteGatewayIsDhcp :' | sed -e 's/^.*: //g')"

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

trim()
{
	echo ${@}
}

if ${IS_TAP} ; then
	if [ "$bRouteGatewayIsDhcp" == "true" ]; then
		if [ -z "$dev" ]; then
			logMessage "Cannot configure TAP interface for DHCP without \$dev being defined. Device may not have disconnected properly."
		else
			set +e
			ipconfig set "$dev" NONE 2>/dev/null
			set -e
		fi
	fi
fi

# Issue warning if the primary service ID has changed
PRIMARY_SERVICE_ID_CURRENT="$( (scutil | grep Service | sed -e 's/.*Service : //')<<- EOF
	open
	show State:/Network/OpenVPN
	quit
EOF)"
if [ "${PRIMARY_SERVICE_ID}" != "${PRIMARY_SERVICE_ID_CURRENT}" ] ; then
	logMessage "Ignoring change of Network Primary Service from ${PRIMARY_SERVICE_ID} to ${PRIMARY_SERVICE_ID_CURRENT}"
fi

# Remove leasewatcher
if ${MONITOR_NETWORK} ; then
	launchctl unload "${WATCHER_PLIST}"
	logMessage "Cancelled monitoring of system configuration changes"
fi

# Restore configurations
DNS_OLD="$(/usr/sbin/scutil <<-EOF
	open
	show State:/Network/OpenVPN/OldDNS
	quit
EOF)"
WINS_OLD="$(/usr/sbin/scutil <<-EOF
	open
	show State:/Network/OpenVPN/OldSMB
	quit
EOF)"
NO_SUCH_KEY="<dictionary> {
  NoSuchKey : true
}"

if [ "${DNS_OLD}" = "${NO_SUCH_KEY}" ] ; then
	scutil <<- EOF
		open
		remove State:/Network/Service/${PRIMARY_SERVICE_ID}/DNS
		quit
EOF
else
	scutil <<- EOF
		open
		get State:/Network/OpenVPN/OldDNS
		set State:/Network/Service/${PRIMARY_SERVICE_ID}/DNS
		quit
EOF
fi

if [ "${WINS_OLD}" = "${NO_SUCH_KEY}" ] ; then
	scutil <<- EOF
		open
		remove State:/Network/Service/${PRIMARY_SERVICE_ID}/SMB
		quit
EOF
else
	scutil <<- EOF
		open
		get State:/Network/OpenVPN/OldSMB
		set State:/Network/Service/${PRIMARY_SERVICE_ID}/SMB
		quit
EOF
fi

logMessage "Restored the DNS and WINS configurations"

# Remove our system configuration data
scutil <<- EOF
	open
	remove State:/Network/OpenVPN/SMB
	remove State:/Network/OpenVPN/DNS
	remove State:/Network/OpenVPN/OldSMB
	remove State:/Network/OpenVPN/OldDNS
	remove State:/Network/OpenVPN
	quit
EOF

exit 0
