#!/bin/sh

DHCP6C="dhcp6c"
DHCP6C_CONF="/etc/dhcp6c.conf"
DHCP6C_IF=$(rdcsman 0x80900700 str)
IP2="/usr/sbin/ip"


UVM=/usr/bin/uvm
UO_PATH=/usr/uo/
UO_FILE=dhcp6c.conf.uo
UO_CONF=dhcp6c.conf

check_dns()
{
	DNS=$(rdcsman 0x900602 u32)
	if [ $DNS -eq 1 ]; then
    	dns1=$(rdcsman 0x900600 str)
    	if [ -n "$dns1" ] ; then
        	echo "dns1 $dns1"
        	echo "nameserver $dns1" >> /etc/resolv.conf
    	fi
    	dns2=$(rdcsman 0x900601 str)
    	if [ -n "$dns2" ] ; then
        	echo "dns2 $dns2"
        	echo "nameserver $dns2" >> /etc/resolv.conf
    	fi
    	wrcsman "0x80900003 \"$dns1 &&
                 0x80900004 \"$dns2"    
	fi
}


check_address()
{
    IPP=$($IP2 -6 addr show dev $DHCP6C_IF | grep global | awk '{print $2}')
	ROUTER=$($IP2 -6 neigh show dev $DHCP6C_IF | grep router | awk '{print $1}')
	if [ -n "$IPP" ] ; then
		if [ -n "$ROUTER" ] ; then
			IP=$(echo $IPP | cut -d '/' -f 1)
        	PL=$(echo $IPP | cut -d '/' -f 2)
			wrcsman "0x80900000 \"$IP && \
                 0x80900001 $PL && \
                 0x80900002 \"$ROUTER"
        	return 0
		fi
    fi
	return 1
}
 
check_connect()
{
    time=0
    while [ $time -le 30 ] ; do
        if check_address ; then
            return 0
        fi
        sleep 1
        time=$(($time+1))
    done
    return 1
}

dhcp6c_start()
{
	wrcsman "0x80900701 1"
	check_dns


	echo 0 > /proc/sys/net/ipv6/conf/$DHCP6C_IF/forwarding
	echo 1 > /proc/sys/net/ipv6/conf/$DHCP6C_IF/accept_ra
	echo 1 > /proc/sys/net/ipv6/conf/$DHCP6C_IF/accept_redirects

	$UVM $UO_PATH/$UO_FILE > /etc/$UO_CONF
	$DHCP6C -c $DHCP6C_CONF -f $DHCP6C_IF &
	if check_connect ; then
		$IP2 -6 route add default dev $DHCP6C_IF
		echo 1 > /proc/sys/net/ipv6/conf/$DHCP6C_IF/forwarding
		wrcsman "0x80900701 2"
	fi
}

dhcp6c_stop()
{
	kill $(cat /var/run/dhcp6c.pid)
	wrcsman "0x80900701 0"
	wrcsman "0x80900000 \"::0 && \
             0x80900001 0 && \
             0x80900002 \"::0"
}

case "$1" in
	start)
		dhcp6c_start
		exit 0
		;;
	stop)
		dhcp6c_stop
		;;
	*)
		exit 1
		;;
esac

exit 0                 

