#!/bin/sh -e
. /usr/share/debconf/confmodule
db_capb backup

log() {
	logger -t inventory-hostname "$@"
}

INVENTORY_FILE=/cdrom/install/inventory.txt

SERIAL=$(cat /sys/class/dmi/id/product_serial)

if [ -z "$SERIAL" ]; then
  log "Warning: No serial number found, skipping."
  exit 0
fi

if [ ! -f "$INVENTORY_FILE" ]; then
  log "Warning: No inventory file found at $INVENTORY_FILE, skipping."
  exit 0
fi

SET_HOSTNAME=$(sed -n -e "s/^${SERIAL}\s\+\([0-9A-Za-z.-]\+\)\$/\1/p" "$INVENTORY_FILE")

if [ -z "$SET_HOSTNAME" ]; then
  db_subst inventory-hostname/get_hostname SERIAL "$SERIAL"
  if ! db_input high inventory-hostname/get_hostname; then
    # question not asked
    exit 0
  fi
  if ! db_go; then
		exit 10 # back up
	fi

  db_get inventory-hostname/get_hostname
  SET_HOSTNAME="$RET"
elif [ "$(echo "$SET_HOSTNAME" | wc -l)" != "1" ]; then
  log "Warning: Multiple inventory entries found for serial number $SERIAL, skipping."
  exit 0
fi

db_set netcfg/get_hostname "$SET_HOSTNAME"
db_fset netcfg/get_hostname seen true