#!/bin/sh
. /lib/functions.sh
. /lib/netifd/netifd-proto.sh
. /lib/net_share.sh

PPP_IPPARAM="$6"

dhcp6cdir="/tmp/dhcp6c"
conffile="$dhcp6cdir/dhcp6c.conf"
dhcp6cpid="$dhcp6cdir/dhcp6c.pid"
dhcp6cscript="/lib/netifd/ppp-dhcp6c.script"
proto_dhcp6c_create_conffile(){
	local ip_mode="$1"
	local dns_mode="$2"
	local ifname="$3"
	local lanif="$4"
	local ip_config="$5"
	local id=`date +%s`

	id=`expr $id % 1000000`

	local id2=`expr $id + 1`

	rm -rf ${dhcp6cdir}
	mkdir -p ${dhcp6cdir}

	if [ "$ip_config" == "specified" ]; then
		echo "interface $ifname {" > "${conffile}"

		[ "$dns_mode" == "dynamic" ] && echo -e "\trequest domain-name-servers;" >> "${conffile}"
		echo -e "\tscript \"$dhcp6cscript\";" >> "${conffile}"

		echo "};" >>  "${conffile}"

	else
		[ "$ip_mode" == "prefix" ] && {
			echo "interface $ifname {" > "${conffile}"
			[ "$ip_config" == "dhcpv6" ] && echo -e "\tsend ia-na $id;" >> "${conffile}"
			echo -e "\tsend ia-pd $id2;" >> "${conffile}"

			[ "$dns_mode" == "dynamic" ] && echo -e "\trequest domain-name-servers;" >> "${conffile}"
			echo -e "\tscript \"$dhcp6cscript\";" >> "${conffile}"

			echo -e "};\n" >>  "${conffile}"

			echo -e "id-assoc na $id {};\n" >> "${conffile}"

			echo "id-assoc pd $id2 {" >> "${conffile}"
			echo -e "\tprefix-interface $lanif {" >> "${conffile}"
			echo -e "\t\tsla-id 1;" >> "${conffile}"
			echo -e "\t};" >>  "${conffile}"
			echo "};" >>  "${conffile}"
		}
		[ "$ip_mode" == "non_temp" ] && {
			echo "interface $ifname {" > "${conffile}"
			[ "$ip_config" == "dhcpv6" ] && echo -e "\tsend ia-na $id;" >> "${conffile}"

			[ "$dns_mode" == "dynamic" ] && echo -e "\trequest domain-name-servers;" >> "${conffile}"
			echo -e "\tscript \"$dhcp6cscript\";" >> "${conffile}"

			echo "};" >>  "${conffile}"

			echo "id-assoc na $id {};" >> "${conffile}"
		}
	fi
}

proto_dhcp6c_create_config() {
	local config="$1"
	local ip_mode="$2"
	local dns_mode="$3"
	local ifname="$4"
	local lanif="$5"
	local ip_config="$6"

	uci_set dhcp6c $config enabled '0'
	uci_set dhcp6c $config interface $ifname
	if [ "$ip_config" == "dhcpv6" ]; then
		uci_set dhcp6c $config enabled '1'
		uci_set dhcp6c $config na '1'
	else
		uci_set dhcp6c $config na '0'
	fi
	if [ "$ip_mode" == "prefix" ]; then
		uci_set dhcp6c $config enabled '1'
		uci_set dhcp6c $config pd '1'
		uci_set dhcp6c lan lanif $lanif
		uci_set dhcp6c lan sla_id '1'
		uci_set dhcp6c lan enabled '1'
		$(multilan_on) && uci_set dhcp6c lan enabled '0'
	else
		uci_set dhcp6c $config pd '0'
	fi

	if [ "$dns_mode" == "dynamic" ]; then
		uci_set dhcp6c $config enabled '1'
		uci_set dhcp6c $config domain_name_servers '1'
	else
		uci_set dhcp6c $config domain_name_servers '0'
	fi
	uci_set dhcp6c $config script "/lib/netifd/ppp-dhcp6c.script"

	uci_commit dhcp6c
}

dhcp6c_write_duid() {
	local client_device="$2"
	local mac="${1:-$(ifconfig "$client_device" | sed -ne 's/[[:space:]]*$//; s/.*HWaddr //p')}"
	local pat="[0-9A-F][0-9A-F]"
	case "$mac" in
		# exactly 6 octets -> assume type 3 (DUID-LL - RFC3315, 9.4)
		$pat:$pat:$pat:$pat:$pat:$pat)
			local oIFS="$IFS"; IFS=":"; set -- $mac; IFS="$oIFS"

			# low endian
			if [ "$(printf \\1 | hexdump -n1 -ve '8/2 "" "%04x" ""')" = "0001" ]; then
				printf \\x0a\\x00

			# big endian
			else
				printf \\x00\\x0a
			fi

			printf \\x00\\x03\\x00\\x06\\x$1\\x$2\\x$3\\x$4\\x$5\\x$6
			logger -t dhcp6c "Using MAC address DUID 00:03:00:06:$1:$2:$3:$4:$5:$6"
		;;
		# at least 7 octets -> could be type 1 or type 2
		$pat:$pat:$pat:$pat:$pat:$pat:*)
			local len_id=":$(echo "$mac" | sed -e 's/[^:]//g')"
			local len_hi=$(printf "%02x" $((${#len_id} / 0xFF)) )
			local len_lo=$(printf "%02x" $((${#len_id} % 0xFF)) )

			# low endian
			if [ "$(printf \\1 | hexdump -n1 -ve '8/2 "" "%04x" ""')" = "0001" ]; then
				printf \\x$len_lo\\x$len_hi

			# big endian
			else
				printf \\x$len_hi\\x$len_lo
			fi

			printf $(echo "$mac" | sed -e 's/^/\\x/; s/:/\\x/g')
			logger -t dhcp6c "Using user provided DUID $mac"
		;;
		*)
			logger -t dhcp6c "Unable to derive DUID from interface '$client_device' and no valid user DUID given"
		;;
	esac
}

config_load /etc/config/network
config_get ip_config $PPP_IPPARAM ip_config
config_get ip_mode $PPP_IPPARAM ip_mode
config_get dns_mode $PPP_IPPARAM dns_mode
config_get ip6addr $PPP_IPPARAM ip6addr
config_get lanif $PPP_IPPARAM lanif
config_get ipv4 $PPP_IPPARAM ipv4
config_get duid_ifname $PPP_IPPARAM ifname
config_get user_duid basic duid

ppp_up="/tmp/pppv6/${IFNAME}"
#rm -rf /tmp/pppv6


[ -n "$LLREMOTE" ] || exit 1

if [ "$ip_config" == "specified" ]; then

	[ -n "$LLREMOTE" ] && {
		proto_init_update "$IFNAME" 1 1
		proto_set_keep 1

		[ -n "$PPP_IPPARAM" ] && {
			[ -n "$IPLOCAL" -a "$ipv4" == "1" ] && proto_add_ipv4_address "$IPLOCAL" 32
			[ -n "$IPREMOTE" -a "$ipv4" == "1" ] && proto_add_ipv4_route 0.0.0.0 0 "$IPREMOTE"
			[ -n "$LLLOCAL" ] && proto_add_ipv6_address "$LLLOCAL" 64
			[ -n "$ip6addr" ] && {
				ip -6 addr add "$ip6addr/64" dev "$IFNAME"
				proto_add_ipv6_address "$ip6addr" 64
			}
			[ -n "$LLREMOTE" ] && proto_add_ipv6_route "::" 0 "$LLREMOTE"
			[ -n "$DNS1" -a "$ipv4" == "1" ] && proto_add_dns_server "$DNS1"
			[ -n "$DNS2" -a "$DNS1" != "$DNS2" -a "$ipv4" == "1" ] && proto_add_dns_server "$DNS2"
		}
		proto_send_update "$PPP_IPPARAM"
	}

else

	[ -n "$PPP_IPPARAM" -a -n "$LLREMOTE" ] && {
		mkdir -p /tmp/pppv6
		[ -n "$IPLOCAL" -a "$ipv4" == "1" ] && echo "$IPLOCAL" > "$ppp_up" || echo "none" > "$ppp_up"
		[ -n "$IPREMOTE" -a "$ipv4" == "1" ] && echo "$IPREMOTE" >> "$ppp_up" || echo "none" >> "$ppp_up"
		[ -n "$LLLOCAL" ] && echo "$LLLOCAL" >> "$ppp_up" || echo "none" >> "$ppp_up"
		[ -n "$LLREMOTE" ] && echo "$LLREMOTE" >> "$ppp_up" || echo "none" >> "$ppp_up"
		[ -n "$DNS1" -a "$ipv4" == "1" ] && echo "$DNS1" >> "$ppp_up" || echo "none" >> "$ppp_up"
		[ -n "$DNS2" -a "$DNS1" != "$DNS2" -a "$ipv4" == "1" ] && echo "$DNS2" >> "$ppp_up" ||  echo "none" >> "$ppp_up"
	}
fi

wait_for_mbit() {
	local ifname="$1"
	local mbit=0

	# wait for RS.
	defcnt=$(cat /proc/sys/net/ipv6/conf/$ifname/router_solicitations)
	echo 1024 > /proc/sys/net/ipv6/conf/$ifname/router_solicitations
	sleep 1
	mbit=`cat /proc/sys/net/ipv6/conf/$ifname/ndisc_mbit`
	while [ "$mbit" == "-1" ];
	do
		sleep 1
		mbit=`cat /proc/sys/net/ipv6/conf/$ifname/ndisc_mbit`
	done
	echo $defcnt > /proc/sys/net/ipv6/conf/$ifname/router_solicitations
	# end of RS.
}

[ -n "$LLREMOTE" ] && {

	echo "2"  > /proc/sys/net/ipv6/conf/$IFNAME/accept_ra
	if [ "$ip_config" == "auto" -o "$ip_config" == "slaac" ]; then
		wait_for_mbit $IFNAME
		echo "1"  > /proc/sys/net/ipv6/conf/$IFNAME/accept_ra_pinfo
	fi

	if [ "$ip_config" == "auto" ]; then
		mbit=`cat /proc/sys/net/ipv6/conf/$IFNAME/ndisc_mbit`
		if [ $mbit -eq 1 ]; then
			ip_config="dhcpv6"
		else
			ip_config="slaac"
		fi
	fi

	
	# need flush the slaac ip addr and ip route
	if [ "$ip_config" != "slaac" ]; then
		echo "1"  > /proc/sys/net/ipv6/conf/$IFNAME/accept_ra
		echo "0"  > /proc/sys/net/ipv6/conf/$IFNAME/accept_ra_pinfo
		local ipv6_addr=`ip -6 addr show ${IFNAME} scope 0 | grep "inet6" | awk '{print $2}'`
		[ -n "$ipv6_addr" ] && {
			ip -6 addr flush $IFNAME $ipv6_addr # flush the slaac ip addr
			ip -6 route flush dev $IFNAME $ipv6_addr # flush the slaac ip route
		}
		ip -6 addr flush $IFNAME scope 0 # flush the slaac ip addr
	fi

	#proto_dhcp6c_create_conffile "$ip_mode" "$dns_mode" "$IFNAME" "$lanif" "$ip_config"
	#local duid_file="/var/dhcp6c_duid"
	#dhcp6c_write_duid "$user_duid" "$duid_ifname" > $duid_file

	#/usr/sbin/dhcp6c -f -p "$dhcp6cpid" -c "$conffile" -t "$PPP_IPPARAM" -u "$duid_ifname" "$IFNAME" &

	proto_dhcp6c_create_config "$PPP_IPPARAM" "$ip_mode" "$dns_mode" "$IFNAME" "$lanif" "$ip_config"
	if [ "$(uci_get dhcp6c ${PPP_IPPARAM} enabled)" == "1" ]; then
		if [ -n "${PPP_SHARE_CMD}" ]; then
			/etc/init.d/dhcp6c start "$PPP_IPPARAM" "/tmp/dhcp6c/proto_dhcp6c_cmd.$PPP_IPPARAM"
               		proto_run_command "$PPP_IPPARAM" $(cat /tmp/dhcp6c/proto_dhcp6c_cmd.$PPP_IPPARAM)
		else
			/etc/init.d/dhcp6c start "$PPP_IPPARAM"
		fi
		sleep 3
                [ -f "/tmp/dhcp6c_duid_$IFNAME" ] && {
                        local duid=`cat "/tmp/dhcp6c_duid_$IFNAME"`
                        [ ${#duid} -ne 0 ] && uci_set dhcp6c ${PPP_IPPARAM} duid $duid
                        uci_commit dhcp6c
                }

	else
		# sync exec for dhcp6c callback script.
		ifname="$IFNAME" interface="$PPP_IPPARAM" new_dhcpc_state="3" \
		/lib/netifd/ppp-dhcp6c.script
	fi
}

[ -d /etc/ppp/ip-up.d  -a -n "$LLREMOTE" ] && {
	for SCRIPT in /etc/ppp/ip-up.d/*
	do
		[ -x "$SCRIPT" ] && "$SCRIPT" "$@"
	done
}
