#!/bin/sh

set -e

# This script writes rc.local in the HDD of installed OS
# so that it can inform the PXE server that the OS is up.

mkdir -p ${BODI_CHROOT_PATH}/etc/oci
cp /etc/oci/pxe-server-ip ${BODI_CHROOT_PATH}/etc/oci/pxe-server-ip

echo "#!/bin/sh

set -e

PXE_SERVER_IP=\$(cat /etc/oci/pxe-server-ip)
CHASSIS_SERIAL=\$(dmidecode -s chassis-serial-number)

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}\$')
	else
		DEFROUTE_IP=\$(hostname -i | grep -E '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\$')
	fi
fi
if [ -n \"\${DEFROUTE_IP}\" ] ; then
	IP_PARAM=\"&ipaddr=\${DEFROUTE_IP}\"
else
	IP_PARAM=\"\"
fi

curl \"http://\${PXE_SERVER_IP}/oci/install-status.php?status=installed&chassis-serial=\${CHASSIS_SERIAL}\${IP_PARAM}\"

if [ -e /var/lib/oci-first-boot ] ; then
	OS_CACERT=/etc/ssl/certs/oci-pki-oci-ca-chain.pem puppet agent --test --debug >/var/log/puppet-first-run 2>&1
	rm -f /var/lib/oci-first-boot
fi

" >${BODI_CHROOT_PATH}/etc/rc.local
chmod +x ${BODI_CHROOT_PATH}/etc/rc.local

# If we see an already prepared hosts file, copy it to the chroot
if [ -e /oci-hosts-file ] ; then
	cat /oci-hosts-file >${BODI_CHROOT_PATH}/etc/hosts
fi

if [ -r /puppet-master-host ] ; then
	MY_HOSTNAME=$(cat /puppet-master-host)
else
	MY_HOSTNAME=$(hostname --fqdn)
fi

# Configure the puppet agent to talk to the puppet master
if [ -e ${BODI_CHROOT_PATH}/etc/puppet/puppet.conf ] ; then
	. /usr/share/openstack-pkg-tools/pkgos_func
	pkgos_add_directive ${BODI_CHROOT_PATH}/etc/puppet/puppet.conf main server=example.com "#puppet master address"
	pkgos_inifile set ${BODI_CHROOT_PATH}/etc/puppet/puppet.conf main server ${MY_HOSTNAME}
fi

# Add stretch-queens backport repo
if ! [ -e ${BODI_CHROOT_PATH}/etc/apt/sources.list.d/stretch-queens.list ] ; then
	echo "deb http://stretch-queens.debian.net/debian stretch-queens-backports main
deb-src http://stretch-queens.debian.net/debian stretch-queens-backports main

deb http://stretch-queens.debian.net/debian stretch-queens-backports-nochange main
deb-src http://stretch-queens.debian.net/debian stretch-queens-backports-nochange main
" >${BODI_CHROOT_PATH}/etc/apt/sources.list.d/stretch-queens.list
	chroot ${BODI_CHROOT_PATH} apt-get update
	chroot ${BODI_CHROOT_PATH} apt-get -y --allow-unauthenticated install openstack-backports-archive-keyring
	chroot ${BODI_CHROOT_PATH} apt-get update
fi
