#!/bin/bash
#	(We have to use bash or ksh instead of the Bourne Shell
#	because we need the printf shell builtin.)
#
#	@(#) set6to4	(c) Dec 2003 by (hoz)
#
#	Set up a 6to4 tunnel on a single Linux host.
#	Use the ip-address at interface $dev to build the
#	6to4 address.
#
#	History:
#	17. Jun 2008 (hoz)
#			Fixed error in option -d and -i usage
#
PATH=/bin:/usr/bin:/usr/sbin:/sbin
progname=`basename $0`
dev="eth0"

defdev=$dev
usage()
{
	echo "usage: $progname [-vn] [-d interface | -i ipv4] up|down" 1>&2
	echo -e "\t-v\t verbose " 1>&2
	echo -e "\t-n\t no exec" 1>&2
	echo -e "\t-d dev\t set 6to4 prefix to the ip address of the given device (default: $defdev" 1>&2
	echo -e "\t-i ipv4\t set 6to4 prefix to the given ip address" 1>&2
	test -n "$1" && echo "$1" 1>&2
	exit 1
}

EXEC=
ECHO=":"

## parse options
while test $# -gt 1
do
	case "$1" in
	-n)	EXEC=":"
		;;
	-v)	ECHO=echo
		;;
	-d)	dev=$2
		shift
		;;
	-i)	dev=""
		ip=$2
		shift
		;;
	-*)	usage "illegal option $1"
		;;
	*)	break
		;;
	esac
	shift
done

# get the current ip address on interface $dev
if test -n "$dev"
then
	ip=`ip addr show dev $dev |
	sed  -n "/inet /s/^[ 	]*inet \([0-9][0-9.]*\).*/\1/p"`
fi

checkip=`echo "0$ip" | tr -d "0-9."`
if test -n "$checkip"
then
	usage "error: parsing of ip address on interface $dev failed: $ip"
fi

ipbytes=`echo $ip | sed "s/\./ /g"`
ip6prefix=`printf 2002:%x%x:%x%x $ipbytes`

echo "debug ip = $ip"

case "$1" in
up)
	$ECHO ip tunnel add tun6to4 mode sit ttl 64 remote any local $ip
	$EXEC ip tunnel add tun6to4 mode sit ttl 64 remote any local $ip
	$ECHO ip link set dev tun6to4 up 
	$EXEC ip link set dev tun6to4 up 
	# the next command adds also an 2002:/16 route to tun6to4
	$ECHO ip -6 addr add ${ip6prefix}::1/16 dev tun6to4
	$EXEC ip -6 addr add ${ip6prefix}::1/16 dev tun6to4

	$EXEC sysctl -w net.ipv6.conf.all.forwarding=1 >/dev/null

	# set "default" ipv6 route (all global prefixes) to
	# 6to4 relay router anycast addr (RFC3056)
	$ECHO ip -6 route add 2000::/3 via ::192.88.99.1 dev tun6to4 metric 1
	$EXEC ip -6 route add 2000::/3 via ::192.88.99.1 dev tun6to4 metric 1
;;	
down)
	$ECHO ip -6 route del 2000::/3 via ::192.88.99.1 dev tun6to4 metric 1
	$EXEC ip -6 route del 2000::/3 via ::192.88.99.1 dev tun6to4 metric 1
	$EXEC sysctl -w net.ipv6.conf.all.forwarding=0  >/dev/null

	$ECHO ip -6 addr del ${ip6prefix}::1/16 dev tun6to4
	$EXEC ip -6 addr del ${ip6prefix}::1/16 dev tun6to4
	$ECHO ip link set dev tun6to4 down
	$EXEC ip link set dev tun6to4 down
	$ECHO ip tunnel del tun6to4 mode sit ttl 64 remote any local $ip
	$EXEC ip tunnel del tun6to4 mode sit ttl 64 remote any local $ip
;;	
*)
	usage "illegal command $1"
esac
