#!/bin/bash

CONF_FILE="/etc/conf.d/hostname.local"

# nothing to do if hostname is already set
if [ -r $CONF_FILE ]
then
    name=$(sed -e '/#/d' -e '/^$/d'< $CONF_FILE)
    [ $name = "localhost" ] || exit 0
fi

# get the serial number
SERIAL="`cf2get "/run/gsl-eeprom/main" "[display-serial]" "serial"`"
if [ -z "${SERIAL}" ]
then
	echo " * Don't know what to set hostname to"
	exit 1
fi

# change the hostname
echo " * Setting system hostname to \"${SERIAL}\""
NEW_FILE="${CONF_FILE}.new"
cat > "${NEW_FILE}" <<EOF
# /etc/conf.d/hostname
#  This file should consist of a single non-comment token, which is the
#  hostname to set.
#
#  This file was created on `isodate -se` by $0
#

${SERIAL}
EOF
[ -s "${NEW_FILE}" ] || exit 1
mv "${NEW_FILE}" "${CONF_FILE}"

# update the live system
hostname -F "${CONF_FILE}"
