#!/bin/sh

set -e

if [ -z "$1" ]; then
    echo "$0: called with no interface" 1>&2
    exit 1;
fi

# Workaround for misfeature in Network Manager, see
# <URL: https://bugs.launchpad.net/ubuntu/+source/network-manager/+bug/293139 >
# Set the variables used by scripts installed by default in Debian Edu
# Wheezy and a few others.  Fake call to dhclient hook.
run_dhclient_exit_hooks() {
    new_interface="$1"
    case "$2" in
	up|vpn-up)
	    reason=BOUND
	    ;;
	down|vpn-down)
            reason=STOP
	    ;;
	*)
	    return
	    ;;
    esac    
    export reason
    if [ "$DHCP4_IP_ADDRESS" ] ; then new_ip_address="$DHCP4_IP_ADDRESS" ; export new_ip_address ; fi
    if [ "$DHCP4_NTP_SERVERS" ] ; then new_ntp_servers="$DHCP4_NTP_SERVERS" ; export new_ntp_servers ; fi
    if [ "$DHCP4_BROADCAST_ADDRESS" ] ; then new_broadcast_address="$DHCP4_BROADCAST_ADDRESS" ; export new_broadcast_address ; fi
    if [ "$DHCP4_SUBNET_MASK" ] ; then new_subnet_mask="$DHCP4_SUBNET_MASK" ; export new_subnet_mask ; fi
    if [ "$DHCP4_HOST_NAME" ] ; then new_host_name="$DHCP4_HOST_NAME" ; export new_host_name ; fi
    for f in /etc/dhcp/dhclient-exit-hooks.d/*; do
	sh $f
    done
}

run_dhclient_exit_hooks "$1" "$2"

case "$2" in
    up|vpn-up)
	if [ -e /etc/debian-edu/config ] ; then
	    . /etc/debian-edu/config
	fi

	# All profiles except Main-Server.  Listing them all to avoid
	# activating this code unless some profile is defined in
	# /etc/debian-edu/config.
	if [ -n "$DHCP4_HOST_NAME" ] && \
	    echo "$PROFILE" | egrep -q 'Workstation|Roaming-Workstation|Thin-Client-Server|Minimal|Standalone' ; then
	    echo "$DHCP4_HOST_NAME" > /etc/hostname
	    logger -t debian-edu-config "Update hostname from DHCP via NetworkManager to '$DHCP4_HOST_NAME'."
	fi
	;;
    down|vpn-down|hostname)
	;;
    *)
	echo "$0: called with unknown action \`$2'" 1>&2
	exit 1
	;;
esac
