#!/bin/bash
# - must be bash: uses bash-specific tricks
#
# openvpn-tun-up-down.sh
#
#
# A script to be used as an OpenVPN routed (tun) up/down script on  Mac OSX 10.4
# - OpenVPN will have assigned peer address as part of the tun  establishment
# - the server may also have pushed routes, and "DHCP"-like  information (DNS Domain and server)
#   - this script extracts any such options and merges them into thecurrent DNS config
#
# Use in your OpenVPN config file as follows:
#
#    up  openvpn-tun-up-down.sh
#
# 2006-09-21    Ben Low    original
#
# 200x-xx-xx    name
#

if [ -z "$dev" ]; then echo "$0: \$dev not defined, exiting"; exit 1; fi


# relevant script_type values are 'up' or 'down'
case "$script_type" in
   up)

     # need to create two Network Service keys:
     # 1. State:/Network/Service/<serviceID>/IPv4 key containing  information about the tunnel
     # 2. State:/Network/Service/<serviceID>/DNS key including the SupplementalMatchDomains key
     # ref. thread: http://lists.apple.com/archives/Macnetworkprog/ 2005/Jun/msg00011.html
     # and http://lists.apple.com/archives/Macnetworkprog/2005/Sep/ msg00047.html
     # - the first thread mentions 'OverridePrimary', but that sets "Both the default route
     #   and the default resolver configuration ..." which is NOT  what we want here.
     # "parse" foreign_options into separate DNS and DOMAIN records
     # - based on Tunnelblick's client.up.osx.sh
     # e.g. (could be any number, in any order; assume consecutive):
     #   foreign_option_1=dhcp-option DOMAIN example.net
     #   foreign_option_2=dhcp-option DNS 10.1.0.1
     unset dns
     unset domain
     n=1; i=0; j=0;
     while o=foreign_option_${n}; o=${!o}; [ "$o" ]
     do
         #echo "$n - $o ($i, $j)"
         case $o in
             'dhcp-option DNS '*)   dns[i++]=${o/dhcp-option DNS /};;
             'dhcp-option DOMAIN '*) domain[j++]=${o/dhcp-option DOMAIN /} ;;
         esac;
         let n++
     done

     echo "dns [${dns[0]}] [${dns[1]}] [${dns[2]}]"
     echo "dom [${domain[0]}] [${domain[1]}] [${domain[2]}]"

     if [ ${#dns[@]} ]; then
         echo "About to set DNS and Domain";
         /usr/sbin/scutil <<EOF
d.init
d.add Addresses * ${ifconfig_local}
d.add DestAddresses * ${ifconfig_remote}
d.add InterfaceName ${dev}
set State:/Network/Service/openvpn-${dev}/IPv4
d.init
d.add ServerAddresses * ${dns[*]}
d.add SupplementalMatchDomains * ${domain[*]}
set State:/Network/Service/openvpn-${dev}/DNS
EOF
     fi

   ;;

   down)

     if [ `/usr/bin/id -u` -eq 0 ]; then
         /usr/sbin/scutil <<EOF
remove State:/Network/Service/openvpn-${dev}/IPv4
remove State:/Network/Service/openvpn-${dev}/DNS
EOF
     fi
   ;;
   *) echo "$0: invalid script_type" && exit 1 ;;
esac

##### FIN

