#!/bin/sh

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DHCP6CBIN=/usr/sbin/dhcp6c
DHCP6CPID=/var/run/dhcp6c.pid
NAME="dhcp6c"
DESC="WIDE DHCPv6 client"

test -x $DHCP6CBIN || exit 0

# Generate the key only once (set this to YES if you want to generate it
# in every boot)
GEN_DHCP6CCTLKEY=NO

# Create the key file for communication between dhcp6ctl and dhcp6c
# The key file cannot be created when installing packet because then every
# osso device would have the same key.
DHCP6CCTLKEY=/etc/wide-dhcpv6/dhcp6cctlkey
if [ "$1" = start ]; then

    # IPv6 enable status is in gconf
    IAP_BASE=/system/osso/connectivity/IAP
    IPV6_KEY=$IAP_BASE/ipv6_enabled
    IPV6=`gconftool-2 -g "$IPV6_KEY" 2> /dev/null`
    if [ -z "$IPV6" ]; then
        # disabled if not found
	exit 0
    fi
    if [ "$IPV6" = 0 ]; then
        # not enabled
	exit 0
    fi
    IFACES=`gconftool-2 -g "$IAP_BASE/ipv6_interfaces" 2> /dev/null`
    if [ -z "$IFACES" ]; then
	echo "DHCPv6 interfaces list not defined in gconf, dhcpv6 is disabled."
	exit 0
    fi
    INTERFACES=`echo "$IFACES" | sed -e 's/\[//g' -e 's/\]//g'`
    [ "X$INTERFACES" != "X" ] || exit 0

    [ ! -r $DHCP6CCTLKEY -o "$GEN_DHCP6CCTLKEY" != "NO" ] && {
        # The key must not be world readable
	umask 066
	echo "Generating ${DHCP6CCTLKEY}..." >&2
	dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64 -e > ${DHCP6CCTLKEY}
	umask 022
    }
fi


# single arg is -v for messages, -q for none
check_status()
{
    if [ ! -r "$DHCP6CPID" ]; then
        test "$1" != -v || echo "$NAME is not running."
        return 3
    fi
    if read pid < "$DHCP6CPID" && kill -0 "$pid" > /dev/null 2>&1; then
        test "$1" != -v || echo "$NAME is running."
        return 0
    else
        test "$1" != -v || echo "$NAME is not running but $DHCP6CPID exists."
        return 1
    fi
}

case "$1" in
	start)
		;;
	stop)
		;;
	restart|force-reload)
		;;
	status)
		echo "Status of $NAME: "
		check_status -v
		exit "$?"
		;;
	*)
		echo "Usage: $0 (start|stop|restart|force-reload|status)"
		exit 1
esac

exit 0
