#!/bin/sh

# default -  don't download code & execute in the background
#       1 -  don't download code & execute in the foreground
#       2 -  download code $ execute in the background
#       3 -  download code & execute in the foreground

if [ "$1" = "1" ] ; then
  download="0"
  foreground="1"
elif [ "$1" = "2" ] ; then
  download="1"
  foreground="0"
elif [ "$1" = "3" ] ; then
  download="1"
  foreground="1"
else
  download="0"
  foreground="0"
fi

proto=$(uci -q get network.wan.proto)
if [ "$proto" = "pppoe" ] ; then
  wan_inf="ppp0"
else
  wan_inf=$(uci -q -P /var/state get network.wan.ifname)
fi

lan_inf=$(uci -q -P /var/state get network.lan.ifname)
lo_inf=$(uci -q -P /var/state get network.loopback.device)
conf_file=/etc/dhcp6/dhcp6c.conf

killall wide-dhcp6c
killall radvd

#wan_up=$(uci -q -P /var/state get network.wan.up)
#if [ "$wan_up" != "1" ] ; then
#  echo "wan connection is fail !!!"
#  exit
#fi

if [ "$download" = "1" ] ; then
  #get file from google code 
  if [ ! -f /tmp/wide-dhcpv6-client_20080615-1_arm.ipk ]; then
	. /sbin/vigorcode.sh
    wget "$PKG_SERVER"wide-dhcpv6-client_20080615-1_arm.ipk -O /tmp/wide-dhcpv6-client_20080615-1_arm.ipk
  fi

  #install package
  if [ ! -f /tmp/opkg-install/usr/sbin/wide-dhcp6c ]; then
    opkg -dest ram install /tmp/wide-dhcpv6-client_20080615-1_arm.ipk
  fi
  
  #check wide-dhcp6c program
  if [ -f /tmp/opkg-install/usr/sbin/wide-dhcp6c ]; then 
    dhcp6_client="/tmp/opkg-install/usr/sbin/wide-dhcp6c"
  else
    echo "fail to install wide-dhcp6c !!!"
	exit
  fi
else
  if [ -f /usr/sbin/wide-dhcp6c ]; then 
    dhcp6_client="wide-dhcp6c"
  else
    echo "wide-dhcp6c isn't exist!!!"
	exit
  fi
fi

#remove lan's ipv6 global address
lan_ipv6=$(uci get ipv6.lan.global_addr)
if [ $lan_ipv6 ]; then
  ifconfig $lan_inf del $lan_ipv6/64 
fi   

#generate config file for wide-dhcp6c
iaid="0"
sla_id=$(uci -q get tspc.@tspc[0].sla_len)
if [ "$sla_id" = "" ]; then
  sla_id="16"
fi

echo "interface $wan_inf {" > $conf_file
echo "    send ia-pd $iaid;" >> $conf_file
echo "    request domain-name-servers,domain-name;" >> $conf_file
if [ "$download" = "1" ] ; then
  echo "    script "\"/tmp/opkg-install/etc/dhcp6/dhcp6c-script\"";" >> $conf_file
else
  echo "    script "\"/etc/dhcp6/dhcp6c-script\"";" >> $conf_file
fi
echo "};" >> $conf_file
echo >> $conf_file
echo "id-assoc pd $iaid {" >> $conf_file
echo "  prefix-interface $lo_inf {" >> $conf_file
echo "    sla-id 0;" >> $conf_file
echo "    sla-len $sla_id;" >> $conf_file
echo "  };" >> $conf_file
echo "  prefix-interface $lan_inf {" >> $conf_file
echo "    sla-id 1;" >> $conf_file
echo "    sla-len $sla_id;" >> $conf_file
echo "  };" >> $conf_file
echo "};" >> $conf_file

# r - start radvd
# P - use 4 byte of mac address as ipv6 prefix iaid
if [ "$foreground" = "1" ] ; then
  $dhcp6_client -drwPSDf -c $conf_file -p /var/run/dhcp6c.pid $wan_inf
else
  $dhcp6_client -drwPSD -c $conf_file -p /var/run/dhcp6c.pid $wan_inf
fi
