#!/bin/sh

set -eu

if [ "$(puavo-conf puavo.admin.personally_administered)" != 'true' ]; then
  exit 0
fi

primary_user="$(puavo-conf puavo.admin.primary_user)"

if [ -n "$primary_user" ]; then
  exit 0
fi

if [ -z "${PAM_USER:-}" ]; then
  logger -p auth.err -s -t puavo-setup-primary-user \
         'PAM_USER environment variable not set'
  exit 1
fi

logger -p auth.notice \
       "making '${PAM_USER}' the primary user by using the override mechanism"

primary_user_override_path='/state/etc/puavo/primary_user_override'

echo "$PAM_USER" > "${primary_user_override_path}.tmp"
mv "${primary_user_override_path}.tmp" "$primary_user_override_path"

puavo-conf puavo.admin.primary_user "$PAM_USER"

# In case we are in user registration mode, we should not try to setup
# anything (reboot is what we really need).
if [ "$(puavo-conf puavo.xsessions.user_registration.enabled)" = 'true' ]; then
  exit 0
fi

#
# Run some puavo-conf scripts because puavo.admin.primary_user value affects
# those and we want those to be effective immediately.
#

status=0

/etc/puavo-conf/scripts/setup_dbus       || status=1
/etc/puavo-conf/scripts/setup_gdm        || status=1
/etc/puavo-conf/scripts/setup_polkit     || status=1
/etc/puavo-conf/scripts/setup_superusers || status=1

exit $status
