#!/bin/sh

# I hereby place this little script into the public domain.
# Author: David Schmitt <david@schmitt.edv-bus.at>, 2006

# See http://www.tldp.org/HOWTO/Linux+IPv6-HOWTO/configuring-ipv6to4-tunnels.html

# extract_field $field
# extracts the value of the space seperated field $field
function extract_field()
{
	sed -e 's/^.*'$1' \([^ ]*\).*/\1/'
}

function log()
{
	[ "$VERBOSITY" = 1 ] && echo "$@"
}

if [ "yes" = "$IF_USE6TO4" ]
then # interface using default gateway being configured

	# extract source ip of the default route
	SRC=$(ip -o route ls dev $IFACE | grep src | extract_field src)
	log found SRC=\"$SRC\"

	# create 6to4 prefix
	PREFIX=$(printf "2002:%02x%02x:%02x%02x" ${SRC//\./ })
	log creating PREFIX=\"$PREFIX\"

	ip tunnel add tun6to4_$IFACE mode sit ttl 64 remote any local $SRC
	ip link set dev tun6to4_$IFACE up 
	ip -6 addr add $PREFIX::1/16 dev tun6to4_$IFACE 
	ip -6 route add 2000::/3 via ::192.88.99.1 dev tun6to4_$IFACE metric 1
	exit 0
fi

if [ -n "$IF_6TO4SUBNET" ]
then
	if [ -z "$IF_6TO4BASE_IFACE" ]
	then
		echo "6to4subnet set, but no 6to4base_iface specified" >&2
		exit 1
	fi

	TUN=tun6to4_$IF_6TO4BASE_IFACE
	# find our current 6to4 prefix
	BASE=$(ip -6 -o addr ls dev $TUN | extract_field inet6 | grep ^2002 )
	PREFIX=${BASE%::*}
	log found BASE=$BASE PREFIX=$PREFIX
	ROUTE=$PREFIX:$IF_6TO4SUBNET::/64
	log Setting route for $ROUTE to $IFACE
	ip route add $ROUTE dev $IFACE
	exit 0
fi
