#!/bin/bash

# This work by http://blog.dest-unreach.be/ is licensed under a Creative
# Commons Attribution-Noncommercial-Share Alike 2.0 Belgium License.

function get_mac_address() {
	# usage: get_mac_address tap0
	# returns the mac-address in __:__:__:__:__:__ form
	/sbin/ifconfig "$1" | grep ether | cut -d' ' -f2
}

function make_SLAAC() {
	# usage: make_SLAAC $prefix $mac
	# assumes $prefix is a /64
	# returns the SLAAC-address
	if [ "${1: -5}" != "::/64" ]; then
		echo "IPv6 prefix does not look like a /64 subnet, aborting" >> /dev/stderr
		exit 1
	fi
	echo "$(echo "$1" | cut -d: -f1-4):$( printf "%x" $(( 0x$(echo "$2" | cut -d: -f1) ^ 0x02 )) )$(echo "$2" | cut -d: -f2):$(echo "$2" | cut -d: -f3)ff:fe$(echo "$2" | cut -d: -f4):$(echo "$2" | cut -d: -f5)$(echo "$2" | cut -d: -f6)/64"
}

/sbin/ifconfig $dev inet6 $( make_SLAAC $OPENVPN_IP6_PREFIX $( get_mac_address $dev ) )
/sbin/route add -inet6 -net $( echo "$OPENVPN_IP6_PREFIX" | sed 's%/% -prefixlen %' ) -iface $dev
for r in $OPENVPN_IP6_ROUTES; do 
	/sbin/route add -inet6 -net $(echo "$r" | sed 's%/% -prefixlen %') $OPENVPN_IP6_GW
done

