#!/bin/sh
# ExecStartPre of ovd-slaveserver.service (Ubuntu asks for this through debconf):
# writes the Session Manager's address from the ovd.session_manager credential into
# slaveserver.conf, e.g. QEMU/Proxmox
#   -smbios type=11,value=io.systemd.credential:ovd.session_manager=sm.example.com
# or "systemd.set_credential=ovd.session_manager:sm.example.com" on the kernel command line.
# Without the credential, slaveserver.conf must already name it.
set -eu

conf=/etc/ovd/slaveserver/slaveserver.conf
cred="${CREDENTIALS_DIRECTORY:-}/ovd.session_manager"

if [ -n "${CREDENTIALS_DIRECTORY:-}" ] && [ -r "$cred" ]; then
	sm=$(tr -d '[:space:]' < "$cred")
	case "$sm" in
		''|*[!A-Za-z0-9.:_-]*)
			echo "ovd.session_manager credential is not a host name or address: '$sm'" >&2
			exit 1
			;;
	esac
	sed -i "s/^session_manager *=.*/session_manager = $sm/" "$conf"
fi

if grep -q '^session_manager *= *\(@SESSION_MANAGER@\)\?$' "$conf"; then
	echo "No Session Manager configured: pass the ovd.session_manager credential or set session_manager in $conf" >&2
	exit 1
fi
