#!/bin/sh

function splitv6addr {
    addrparts=($(echo $1 | sed 's/\./ /g'))
    if (( ${#addrparts[*]} != 4 )) ; then
	return 1
    fi
    for x in ${addrparts[*]}; do
	if (( $x < 0 )) || (( $x > 255 )) ; then
	    echo "$x is not a valid part of a v4 address"
	    return 1
	fi
    done
    return 0
}

# quit immediately if anything goes wrong
set -e

# get our ipv4 address from the ip command
v4addr=$(ip -f inet addr show eth0 | tail -1 | awk '{print $2}' | cut -d/ -f1)
# invent a v6 address to use based on the 6to4 schema (2002:<v4addr>::1)
splitv6addr "$v4addr"
v6addr=$(echo $v4addr | printf "2002:%02x%02x:%02x%02x::1" ${addrparts[*]})

# now to do the actual work...

# create the tunnel pseudodevice
ip tunnel add tun6to4 mode sit ttl 30 remote any local $v4addr
ip link set dev tun6to4 up
# assign the v6 address to the tunnel
ip -6 addr add $v6addr/16 dev tun6to4
# add a route for global scope v6 addresses via the anycast router
ip -6 route add 2000::/3 via ::192.88.99.1 dev tun6to4 metric 1
