#!/bin/bash

# DHCPv6
target_dhcphook="/etc/dhcp3/dhclient-exit-hooks.d/dhclient-ipv6-exit-hook"
target_servicefile="/etc/systemd/system/dhclient6.service"

cat >$target_dhcphook << 'EOF'
#  /etc/dhcp3/dhclient-exit-hooks.d/dhclient-ipv6

# Interfaces that should obtain a /64 prefix
IPV6_INTERFACES=(eth0)
INT_ADDRESS="::0d"

###

ipv6_prefix_setup() {
	# $1 is the ethernet interface
	# $2 is the suffix to use
	ethiface=$1
	suffix=$2
	
	current_ip=$(ip -6 addr show dev $ethiface scope global | awk '/inet6/ {print $2}' | grep -v '^fd' )
	current_prefix=$(echo $current_ip | sed -e 's@::.*/64@::/64@')
  
	# To generate new IP, need to take new prefix, add 8 bits
	new_ip=$( echo $new_ip6_prefix | sed -e 's/00::\/.*//g' )
	new_ip="$new_ip$suffix"

	if [ "$new_ip" != "$current_ip" ]
	then
		if [ "$current_ip" != "" ]
		then
			/sbin/ip -6 addr delete "$current_ip" dev $ethiface
		fi
	/sbin/ip -6 addr add "$new_ip" dev $ethiface
  
	fi
}

case "$reason" in
  BOUND6|REBIND6)
    # We will get called twice here - once for the temp address
    # and once for the prefix. We only care about the prefix.
    if [ ! -z "$new_ip6_prefix" ] ; then
	for interface in "${IPV6_INTERFACES[@]}"
	do
		suffix=$( echo ${interface} | /usr/bin/md5sum | awk '{ print substr($1,3,2) }' )
		suffix="$suffix$INT_ADDRESS/64"
		ipv6_prefix_setup ${interface} $suffix
	done
	/bin/systemctl restart radvd.service >/dev/null 2>&1
    fi
    ;;
esac

EOF

cat >$target_servicefile << 'EOF'
#/etc/systemd/system/dhclient6.service
[Unit]
Description=dhclient for sending IPv6 DUID
After=network.target auditd.service vyatta-router.service netplug.service

[Service]
Type=forking
ExecStartPre=/config/scripts/generate_dhcpv6_configfile.sh
ExecStart=/sbin/dhclient -6 -P -nw -cf /etc/dhcp3/dhclient6_eth1_832.conf -pf /var/run/dhclient6_eth1_832.pid -lf /var/run/dhclient6_eth1_832.leases eth1.832
NonBlocking=yes                               
Restart=always
RestartSec=60

[Install]
WantedBy=multi-user.target
EOF

