#!/bin/sh

# This script is called once when the server boots.

set -e

oci-wait-for-networking
SYSTEM_SERIAL=$(oci-system-serial)
PXE_SERVER_IP=$(cat /etc/oci/pxe-server-ip)

curl "http://${PXE_SERVER_IP}/oci/install-status.php?status=live&chassis-serial=${SYSTEM_SERIAL}"

# We want that the hostname in live includes the chassis/system serial number
# because that way, we get LLDP to use it, which is nice from the switch side.
# This hostname is also used on the DHCP, which is also useful to tell which
# server is requesting an IP. That also helps to differentiate early DHCP
# requests (ie: PXE boot at BIOS/EFI time) from renewing of leases once the
# os is in the Live distro.
CALCULATED_HOSTNAME=${SYSTEM_SERIAL}.oci-debian-live
CONFIGURED_HOSTNAME=$(cat /etc/hostname)

if ! [ "${CALCULATED_HOSTNAME}" = "${CONFIGURED_HOSTNAME}" ] ; then
	# Popuplate /etc/hostname and /etc/hosts
	echo "${CALCULATED_HOSTNAME}" >/etc/hostname
	if ! grep -q "${CALCULATED_HOSTNAME}" /etc/hosts ; then
		DEFROUTE_IF=$(awk '{ if ( $2 == "00000000" ) print $1 }' /proc/net/route)
		if [ -n "${DEFROUTE_IF}" ] ; then
			if [ -x /bin/ip ] ; then
				DEFROUTE_IP=$(LC_ALL=C ip addr show "${DEFROUTE_IF}" | grep inet | head -n 1 | awk '{print $2}' | cut -d/ -f1 | grep -E '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$' || true)
			fi
		fi
		if [ -z "${DEFROUTE_IP}" ] ; then
			DEFROUTE_IP=$(hostname -i | grep -E '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$' || true)
		fi
		if [ -n "${DEFROUTE_IP}" ] ; then
			echo "${DEFROUTE_IP}	${CALCULATED_HOSTNAME}" >>/etc/hosts
		fi
	fi

	# Set the hostname
	hostname "${CALCULATED_HOSTNAME}"

	# Restart lldpd so it starts advertizing our (new) hostname to the switch
	if [ -x /etc/init.d/lldpd ] ; then
		invoke-rc.d lldpd restart
	fi
fi

if [ -e /etc/oci/live-image-dell-ipmi ] ; then

	DELL_IPMI_REPO=$(cat /etc/oci/setup-dell-ipmi-intarget-repo)

	# Note that "stretch" is always correct, in Buster as well.
	if ! [ -e /etc/apt/sources.list.d/dell-ipmi.list ] ; then
		echo "deb ${DELL_IPMI_REPO} stretch main" >/etc/apt/sources.list.d/dell-ipmi.list
		apt-get update
	fi
	if ! dpkg-query -W srvadmin-idracadm8 >/dev/null 2>/dev/null ; then
		apt-get install -y srvadmin-idracadm8
	fi

	IDRAC_TYPE=$(ipmitool sdr elist mcloc | awk '{print $1}')
	if [ "${IDRAC_TYPE}" = "iDRAC6" ] || [ "${IDRAC_TYPE}" = "iDRAC7" ] ; then
		TO_INSTALL=""
		if ! dpkg-query -W syscfg >/dev/null 2>/dev/null ; then
			TO_INSTALL="${TO_INSTALL} syscfg"
		fi
		if ! dpkg-query -W libssl1.0.0 >/dev/null 2>/dev/null ; then
			TO_INSTALL="${TO_INSTALL} libssl1.0.0"
		fi
		if [ -n "${TO_INSTALL}" ] ; then
			apt install -y ${TO_INSTALL} || true
		fi
	fi
fi
