#!/bin/sh
#
# Completely automated 6to4 tunnel script. Just run and be happy.
# Andreas Henriksson <andreas@fatal.se>, 2008-08-19.
#

set -e
set -u

# find interface and ipv4 address.
IF="$(ip -4 route list default | sed -e 's/.*dev //' | cut -d' ' -f1)"
IP4="$(ip -4 addr show dev $IF scope global | grep inet | head -n1 | sed -e 's/.*inet //' | cut -d'/' -f1)"

# generate 6to4 ipv6 address.
IP6=$(printf "2002:%02x%02x:%02x%02x::1" `echo $IP4 | tr "." " "`)

# make sure we have a real address.
if [ "$(echo $IP4 | cut -d'.' -f1)" = "10" ] || 
		[ "$(echo $IP4 | cut -d'.' -f1,2)" = "192.168" ] ||
		[ "$(echo $IP4 | cut -d'.' -f1,2)" = "172.16" ] ||
		[ "$(echo $IP4 | cut -d'.' -f1,2)" = "172.17" ] ||
		[ "$(echo $IP4 | cut -d'.' -f1,2)" = "172.18" ] ||
		[ "$(echo $IP4 | cut -d'.' -f1,2)" = "172.19" ] ||
		[ "$(echo $IP4 | cut -d'.' -f1,2)" = "172.20" ]; then
	echo "ERROR: You seem to be stuck behind NAT. Set up the tunnel on the computer with real internet access and use it as an ipv6 router." >&2
	exit 1
fi

# clean up old cruft.
ip tunnel del tun64 > /dev/null 2>&1 || true

# set up new tunnel.
ip tunnel add tun64 mode sit remote any local $IP4
ip link set dev tun64 up
ip -6 addr add $IP6/48 dev tun64

ip -6 route add 2000::/3 via ::192.88.99.1 dev tun64 metric 1

# test if it works and report status.
if which wget > /dev/null 2>&1 ; then
	if wget -T 10 -O/dev/null http://ipv6.sunet.se 2>/dev/null ; then
	       	echo 'It works, welcome to the future!'
	else
	       	echo "Hmm.... can\'t reach test site!"
	fi
elif which curl > /dev/null 2>&1 ; then
	if curl -o /dev/null http://ipv6.sunet.se 2>/dev/null ; then
	       	echo 'It works, welcome to the future!'
	else
	       	echo "Hmm.... can\'t reach test site!"
	fi
elif which elinks > /dev/null 2>&1 ; then
       	if elinks -dump http://ipv6.sunet.se > /dev/null 2>&1 ; then
	       	echo 'It works, welcome to the future!'
	else
	       	echo "Hmm.... can\'t reach test site!"
	fi
else
	echo "Link configured, but untested..."
fi


