#! /bin/sh

# (C)2005 by Carsten Gross <linux-software@siski.de>

# Define PATHs of important programs
IP=/usr/sbin/ip
IFCONFIG=/sbin/ifconfig

# The external interface
WAN_DEVICE=ppp0
MYIP=`ip -o -4 addr show ${WAN_DEVICE} |cut -f 7 -d ' ' |cut -f 1 -d'/'`
# or configured statically
# MYIP=your.v4.address.here

# The internal device. It will be configured with 
# the first available network 
LAN_DEVICE=br0

# 192.88.99.1 is the tunnel provider as described in
# RFC3068.
# Normally it is not necessary to change it.
# Of course it is possible to use any other 6to4 gateway.
TUNNELPROVIDER=192.88.99.1

# Stuff below shouldn't need changes...

# calculate 192.168.0.1 into 2002:c0a8:0001
v6ip () {
	O1="`echo $MYIP|cut -f 1 -d'.'`"
	O2="`echo $MYIP|cut -f 2 -d'.'`"
	O3="`echo $MYIP|cut -f 3 -d'.'`"
	O4="`echo $MYIP|cut -f 4 -d'.'`"
	S="2002:`convoct $O1``convoct $O2`:`convoct $O3``convoct $O4`"
	echo $S
}

# helper function for the above function
convoct () {
	LN="`expr $1 % 16`"
	HN="`expr $1 / 16`"
	LS="`expr substr 123456789abcdef $LN 1`"
	HS="`expr substr 123456789abcdef $HN 1`"
	if [ "x${LS}" = "x" ] ; then
		LS="0"
	fi
	if [ "x${HS}" = "x" ] ; then
		HS="0"
	fi
	echo "$HS$LS";
};	

MYV6PREFIX="`v6ip $MYIP`"

$IP tunnel del tun6to4
$IP tunnel add tun6to4 mode sit remote any local ${MYIP} ttl 64
$IP link set dev tun6to4 up mtu 1400
$IP -6 addr add ${MYV6PREFIX}::1/16 dev tun6to4
# remove old devices, to avoid stale entries
$IP -6 addr del ${MYV6PREFIX}:1::1/64 dev ${LAN_DEVICE} 2>/dev/null

# Setup outgoing route...
$IP -6 route add ::/0 via ::${TUNNELPROVIDER} dev tun6to4 metric 1

$IP -6 addr add ${MYV6PREFIX}:1::1/64 dev ${LAN_DEVICE}

cat > /tmp/radvd.conf <<EOF
# autogenerated configuration for radvd
interface ${LAN_DEVICE}
{
        AdvSendAdvert on;
        AdvHomeAgentFlag off;
        MinRtrAdvInterval 10;
        MaxRtrAdvInterval 30;
        prefix ${MYV6PREFIX}:1::/64
        {
                AdvOnLink on;
                AdvAutonomous on;
                AdvRouterAddr off;
                AdvPreferredLifetime 240;
                AdvValidLifetime 600;
        };

};
EOF

exit 0

