#!/bin/sh
INTERFACES="/etc/network/interfaces"
RADVD_CONF="/etc/radvd.conf"
RADVD_INIT="/etc/init.d/radvd"
FIREWALL="/etc/rc.local.firewall"
ROUTER_IP=`wget -qO- http://192.168.0.1/ |grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+' |grep -Ev '^(192\.168|255)\.' |head -1`
if [ -z "$ROUTER_IP" ]; then
  echo "Router probably offline" >&2
  ifdown tun6to4
  $RADVD_INIT stop
  exit 1
fi
PREFIX=$(printf 2002:%02x%02x:%02x%02x $(echo $ROUTER_IP |sed 's/\./ /g') | sed 's/:0\+//g')
if grep -q $PREFIX $INTERFACES; then exit 0; fi
sed -i "s/2002:[0-9a-f]\+:[0-9a-f]\+:/$PREFIX:/g" $INTERFACES $RADVD_CONF $FIREWALL
ifdown tun6to4; ifup tun6to4
$RADVD_INIT restart
$FIREWALL
