#!/bin/sh
# Steven Bromley

PART=/etc/NOS
MAC_FILE="$PART/MAC"
MAC=$1

# Generate a random hardware address.
if [ ${#MAC} -ne 17 ]; then
   RANDOM=$$  # Seed the generator with the PID

   MAC="00:10:a1"  # Kendin Semiconducter (Micrel/Kendin) address block
   MAC="${MAC}$(
      printf ':%02x' $((${RANDOM}%256))
      printf ':%02x' $((${RANDOM}%256))
      printf ':%02x' $((${RANDOM}%256))
   )"
fi


# Is someone else already working on the persistent partition?
if ! grep -q "${PART}" /proc/mounts; then
   echo "FATAL: Persistent partition not mounted" >&2
   exit 1
fi
if [ "$(grep "${PART}" /proc/mounts | cut -f 4 -d ' ')" != "ro" ]; then
   unset REMOUNTRO
else
   REMOUNTRO=true
fi


# Record the address.
set -e
(  mount -o remount,rw "${PART}"
   echo "${MAC}" > "${MAC_FILE}"

   sync
   if [ -n "${REMOUNTRO}" ]; then
      mount -o remount,ro "${PART}"
   fi
) || (
   echo "FATAL: Unable to set MAC!" >&2
   exit 1
)
set +e
echo "MAC changed."
echo "${MAC}"


# Set the hostname to reflect the change.
# This, arguably, should not be done in a tool called 'mac-init'

CMAC="$(cut -f 4,5,6 -d ':' "${MAC_FILE}" 2>/dev/null | tr ':' '-')"
HOSTNAME="$(head -n 1 /etc/HOSTNAME 2>/dev/null)"
if [ -z "${HOSTNAME}" ]; then
   HOSTNAME="composer.invalid.domain"
fi

HOSTBASE="$(echo "${HOSTNAME}" | cut -f 1 -d . | sed 's/-..-..-..//')"
HOSTDOMAIN="$(echo "${HOSTNAME}" | cut -f 2- -d .)"
HOSTNAME="${HOSTBASE}${CMAC:+-${CMAC}}${HOSTDOMAIN:+".${HOSTDOMAIN}"}"
unset CMAC HOSTBASE HOSTDOMAIN

echo ${HOSTNAME} > /etc/HOSTNAME
echo ${HOSTNAME}
