#! /bin/bash

### Find the global IPv4 address for this host:
if [ -n "$1" ] ; then
  # Use command line argument, if present
  GLOB_IP4=$1
else
  # Use the address of the interface that has the default route
  DEV=$(route | awk '/^default / { print $8 }' | head -1)
  #[ -z "$DEV" ] || GLOB_IP4=$(ifconfig "$DEV" | sed -n 's/ *inet addr:\([0-9.]*\).*/\1/p')
  [ -z "$DEV" ] || GLOB_IP4=$(ifconfig "$DEV" | sed -n 's/ *inet \([0-9.]*\).*/\1/p')
fi
if [ -z "$GLOB_IP4" ] ; then
  echo >&2 "No IPv4 address for the 6to4 tunnel"
  exit 1
fi

### Compute the 6TO4 tunnel IPv6 address:
GLOB_IP6TO4=$(printf "2002:%02x%02x:%x%02x::1" $(echo $GLOB_IP4 | tr . ' '))

case "$GLOB_IP6TO4" in
    # 10.0.0.0/8, 172.16.0.0.0/12, 192.168.0.0/16, 127.0.0.0/8
    2002:0a*|2002:1f1*|2002:c0a8:*|2002:7f*)
	echo >&2 "6to4 needs a global IPv4 address, $GLOB_IP4 on $DEV is local"
	exit 1
esac
	     
### Setup the tunnel
ip tunnel add tun6to4 mode sit remote any local $GLOB_IP4 ttl 64 &&
ip link set dev tun6to4 up &&
ip addr add $GLOB_IP6TO4/16 dev tun6to4 &&
ip route add 2000::/3 via ::192.88.99.1 dev tun6to4 metric 1024

exit 0
