#!/bin/sh

set -e
set -x

DIRNAME=$(dirname $0)

DEBIAN_RELEASE=${BODI_RELEASE}

if [ -z "${OPENSTACK_RELEASE}" ] ; then
	if dpkg-query -W lsb-release ; then
		CODE_NAME=$(lsb_release -c -s 2>/dev/null)

		case "${CODE_NAME}" in
		"buster")
			OPENSTACK_RELEASE=rocky
		;;
		"bullseye")
			OPENSTACK_RELEASE=victoria
		;;
		"bookworm")
			OPENSTACK_RELEASE=zed
		;;
		"trixie")
			OPENSTACK_RELEASE=dalmatian
		;;
		*)
			echo "Warning: Unknown debian release."
			OPENSTACK_RELEASE=""
		;;
		esac
	else
		# Fallback to current stable release.
		echo "Warning: lsb-release not install, cannot guess debian release."
		OPENSTACK_RELEASE=""
	fi
fi

# Add octavia's backport repo if we know which one to use.
# Otherwise, simply use what's in current Debian stable release.
if [ -n "${OPENSTACK_RELEASE}" ] ; then
	mkdir -p ${BODI_CHROOT_PATH}/etc/apt/keyrings
	wget http://${DEBIAN_RELEASE}-${OPENSTACK_RELEASE}.debian.net/debian/dists/pubkey.gpg -O ${BODI_CHROOT_PATH}/etc/apt/keyrings/${DEBIAN_RELEASE}-${OPENSTACK_RELEASE}.asc
	echo "deb [signed-by=/etc/apt/keyrings/${DEBIAN_RELEASE}-${OPENSTACK_RELEASE}.asc] http://${DEBIAN_RELEASE}-${OPENSTACK_RELEASE}.debian.net/debian ${DEBIAN_RELEASE}-${OPENSTACK_RELEASE}-backports main
deb [signed-by=/etc/apt/keyrings/${DEBIAN_RELEASE}-${OPENSTACK_RELEASE}.asc] http://${DEBIAN_RELEASE}-${OPENSTACK_RELEASE}.debian.net/debian ${DEBIAN_RELEASE}-${OPENSTACK_RELEASE}-backports-nochange main
" >${BODI_CHROOT_PATH}/etc/apt/sources.list.d/${DEBIAN_RELEASE}-${OPENSTACK_RELEASE}.list

	chroot ${BODI_CHROOT_PATH} apt-get update
fi

# Add octavia-agent to the image
chroot ${BODI_CHROOT_PATH} apt-get install octavia-agent anacron -y

# Disable haproxy by default
chroot ${BODI_CHROOT_PATH} update-rc.d haproxy disable
chroot ${BODI_CHROOT_PATH} update-rc.d -f haproxy remove

# Fix defaults of haproxy logrotate, so that we don't keep too much
# log files, as the Amphora image is kind of super small.
echo "/var/log/haproxy.log {
    hourly
    rotate 3
    missingok
    notifempty
    compress
    copytruncate
}" >${BODI_CHROOT_PATH}/etc/logrotate.d/haproxy
cp ${BODI_CHROOT_PATH}/etc/cron.daily/logrotate ${BODI_CHROOT_PATH}/etc/cron.hourly
mkdir -p ${BODI_CHROOT_PATH}/etc/systemd/system/logrotate.timer.d
echo "[Timer]
OnCalendar=hourly
" >${BODI_CHROOT_PATH}/etc/systemd/system/logrotate.timer.d/hourly.conf
