#!/bin/sh

HOMECTL_STATE="absent"
HOMECTL=$(homectl list -EE | jq '.[] | select(.name=="'${FLL_LIVE_USER}'")')
if [ -n "${HOMECTL}" ]; then
	HOMECTL_STATE=$(echo "${HOMECTL}" | jq -r '.state')
fi

case "${HOMECTL_STATE}" in
	fixating*|unfixated|inactive)
		FLL_LIVE_USER_GROUPS=$(echo "${FLL_LIVE_USER_GROUPS}" | sed -e 's/\s/,/g')
		# A home matching installed systemd-homed keys is present but may not
		# have been blessed by the system yet (unfixated). Activate discovered
		# homes in anticipation of autologin into the live desktop environment.
		homectl activate "${FLL_LIVE_USER}"
		if [ "$?" = "0" ]; then
			homectl update "${FLL_LIVE_USER}" \
				--member-of="${FLL_LIVE_USER_GROUPS}" \
				--session-launcher="${FLL_XSESSION}" \
				--session-type="${FLL_XTYPE}" \
				--auto-login=yes
		fi
		;;
	absent|*)
		FLL_LIVE_USER_GROUPS=$(echo "${FLL_LIVE_USER_GROUPS}" | sed -e 's/\s/,/g')
		homectl create "${FLL_LIVE_USER}" \
				--real-name="${FLL_LIVE_USER}" \
				--member-of="${FLL_LIVE_USER_GROUPS}" \
				--session-launcher="${FLL_XSESSION}" \
				--session-type="${FLL_XTYPE}" \
				--auto-login=yes \
				--storage=directory
		homectl activate "${FLL_LIVE_USER}"
		;;
esac
