#!/bin/sh
# Startup and shutdown helper script for CUDN VPN connections created by
# network-manager-strongswan, set up on Ubuntu 14.04 as described at
# https://help.uis.cam.ac.uk/service/devices-networks-printing/remote-access/uis-vpn/ubuntu1404
#
# Placed this file into
#
#   /etc/NetworkManager/dispatcher.d/
#
# to arrange that only CUDN traffic goes via the VPN.
#
# Optionally also link this file from
#
#   /etc/NetworkManager/dispatcher.d/pre-down.d
#
# to arrange that unused automounted directories are unmounted
# before the VPN goes down.
#
# Markus Kuhn <mgk25>

IFACE="$1"
ACTION="$2"

case "$2" in
    vpn-up)
	# Correct routing table 220 (which is where strongSwan adds its
	# default route), such that only traffic to the main CUDN
	# address ranges goes via the CUDN VPN, as opposed to all traffic.
	# CUDN ranges: https://help.uis.cam.ac.uk/service/devices-networks-printing/network-services/infoinstitutions/ip/cam-ip-ranges
	if ip -4 route show table 220 | grep -q default ; then
            for net in 128.232.0.0/16 129.169.0.0/16 131.111.0.0/16 ; do
		ip route add `ip -4 route show table 220 | grep default | sed -e "s'default'$net'"` table 220
	    done
            ip route delete default table 220
        fi
	;;
    vpn-pre-down)
	# Unmount unused automounted directories before the VPN goes down.
	killall -q -s USR1 automount && sleep 1
	;;
esac
