#! /bin/sh
#
# (C) Copyright 2002, 2004-2007 Axis Communications AB, LUND, SWEDEN
# This file is released under the GPL v2.

local _serno _dhcp_restarted _iface

# FIXME: If this is to work for different interfaces we cannot hardcode
#        that we shall use eth0.
. /etc/conf.d/net.eth0

. /etc/init.d/functions.sh
. /etc/conf.d/hostname

[ -e $RCLIB/sh/rc-dhcp.sh ] && . $RCLIB/sh/rc-dhcp.sh

case "$1" in
	start|restart)
		begin "Setting hostname"

		if [ "$HOSTNAME" = "" ]; then
			[ -x /bin/bootblocktool ] &&
				_serno=$(bootblocktool -x SERNO | tr A-F a-f)
			if [ -z "$_serno" ]; then
				warning "$0: Cannot determine serial number!"
				HOSTNAME="axis"
				information "no serial number," \
					"using default hostname: $HOSTNAME"
			else
				# Add prefix to serial number and update file.
				HOSTNAME="axis-$_serno"
				information "saving generated hostname:" \
					"\"$HOSTNAME\""
				echo "HOSTNAME=\"$HOSTNAME\"" > \
					/etc/conf.d/hostname
			fi
		fi

		# Running dhcp_ifaces isn't enough to find out if we're using
		# dhcp since timing issues will arise if another script is
		# disabling dhcp at the same time.
		if [ "$BOOTPROTO" = dhcp ]; then
			_dhcp_restarted=$(dhcp_ifaces)
			if [ "$_dhcp_restarted" ]; then
				stop_dhcp $_dhcp_restarted
			fi
		fi

		# Hostname may be empty so we must not (and will not) fail if
		# it is.
		hostname "$HOSTNAME" && information "hostname: \"$HOSTNAME\""

		# source conf file again to get updated DHCP_CLIENT:
		. /etc/conf.d/net.eth0

		# bring em back up again
		if [ "$_dhcp_restarted" ]; then
			for _iface in $_dhcp_restarted; do
				start_dhcp "$_iface"
			done
		fi

		end $?
		;;
	stop)
		begin "Removing hostname"
		hostname "" && information "hostname: \"\""
		end $?
		;;
	*)
		error "Usage: $0 start|stop"
		;;
esac

exit 0
