#!/bin/sh

. /etc/net6conf/6data.conf
outfile=/tmp/ipv6_auto_output
BASEDIR="/etc/net6conf"

start()
{
	$ECHO -n "Detecting..." > ${outfile}
	/sbin/detwanv6 ${WAN} ${outfile} &
	while [ "x$(cat ${outfile})" = "xDetecting..." ]; do
		sleep 5
		if ! detwanv6_is_running && [ "x$(cat ${outfile})" = "xDetecting..." ]; then
			/sbin/detwanv6 ${WAN} ${outfile} &
		fi
	done
	# Wait detwanv6 release RAW socket
	/usr/bin/killall detwanv6

	sleep 2

	case `cat ${outfile}` in
		"6to4 Tunnel")
			${BASEDIR}/6to4 start
		;;
		"6rd Tunnel")
			${BASEDIR}/6rd start
		;;
		"DHCP")
			${BASEDIR}/6dhcpc start
		;;
		"Auto Config")
			${BASEDIR}/6autoconf start
		;;
		"Pass Through")
			${BASEDIR}/6bridge start
		;;
		*)
		;;
	esac
}

detwanv6_is_running()
{
	if ps | grep detwanv6 | grep -v grep >&- 2>&- ; then
		return 0
	else
		return 1
	fi
}

stop()
{
	$ECHO -n "Stop 6autodet"
	detwanv6_is_running && /usr/bin/killall detwanv6
	rm -f ${outfile}
}

case "$1" in
	"start")
		start
	;;
	"stop")
		stop
	;;
	"restart")
		stop
		start
	;;
esac
