#!/bin/sh
#
# Completely automated "figure out ipv6 network and configure my LAN" script.
#
# Makes some assumptions:
#  * radvd is installed and configured.
#  * The lan interface is the first interface listed in /etc/radvd.conf
#
# Andreas Henriksson <andreas@fatal.se>, 2009-09-22.
#

set -e
set -u

#if [ "$EXTIF" = "" ]; then
EXTIF=$(ip -6 ro sh 2002::/16 | head -n 1 | sed -e 's/.*dev \([A-Za-z0-9]*\).*/\1/')
#fi

if [ "$EXTIF" = "" ]
then
	echo "ERROR: could not find interface with default ipv6 route!" >&2
	exit 1
fi

SUBNET=$(ip -6 a sh dev tun64 scope global | grep ' *inet6 '  | grep -v 'inet6 ::' | sed -e 's/.*inet6 \([a-f0-9:]*::\).*/\1/')

if [ "$SUBNET" = "" ]
then
	echo "ERROR: could not find ipv6 subnet." >&2
	exit 2
fi

INTNET=$(echo $SUBNET | sed -e 's/::$/:10:/')

if [ ! -f /etc/radvd.conf ]
then
	echo "ERROR: no /etc/radvd.conf found!" >&2
	exit 3
fi

# find first "interface foobar" in /etc/radvd.conf
INTIF=$(sed -ne '/^interface/{s/interface \([A-Za-z0-9]*\)/\1/p;q}' /etc/radvd.conf)

if [ "$INTIF" = "" ]
then
	echo "ERROR: internal interface not found (searched /etc/radvd.conf)" >&2
	exit 4
fi

if [ $(grep -c '^interface ' /etc/radvd.conf) != 1 ]
then
	echo "Warning: script will use first interface in /etc/radvd.conf: $INTIF" >&2
fi

# add the first address to the internal interface.
ip -6 addr del ${INTNET}:1/64 dev $INTIF > /dev/null 2>&1 || true
ip -6 addr add ${INTNET}:1/64 dev $INTIF

echo "Added ${INTNET}:1/64 to $INTIF."

# replace the first occurence of "prefix" with the internal subnet.
sed -ie "0,/prefix .*/s//prefix ${INTNET}:\/64/" /etc/radvd.conf

echo "Reconfigured radvd to use subnet ${INTNET}:/64."

[ ! -f /etc/init.d/radvd ] || /etc/init.d/radvd reload

