#!/bin/sh

set -eu

if [ "$(puavo-conf puavo.pm.lidsuspend.enabled)" = 'true' \
       -a ! -e /state/.suspend_if_lid_closed ]; then
  handle_lid_switch_action='suspend'
else
  handle_lid_switch_action='ignore'
fi

handle_lid_switch_docked_action="$(puavo-conf puavo.pm.lidswitchdocked.action)"
if [ -z "$handle_lid_switch_docked_action" ]; then
  handle_lid_switch_docked_action='ignore'
fi

puavo_os_group_users=$(getent passwd \
                         | awk -F: -v gid="$(id -g puavo-os)" '
                             $4 == gid {
                               groups = (groups != "" ? (groups " " $1) : $1)
                             }
                             END { print groups }
                           ')

cat <<EOF > /etc/systemd/logind.conf.tmp
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.
#
# See logind.conf(5) for details

[Login]
#NAutoVTs=6
#ReserveVT=6
KillUserProcesses=yes
#KillOnlyUsers=
KillExcludeUsers=root ${puavo_os_group_users}
InhibitDelayMaxSec=60
HandlePowerKey=poweroff
#HandleSuspendKey=suspend
#HandleHibernateKey=hibernate
HandleLidSwitch=${handle_lid_switch_action}
HandleLidSwitchDocked=${handle_lid_switch_docked_action}
#PowerKeyIgnoreInhibited=no
#SuspendKeyIgnoreInhibited=no
#HibernateKeyIgnoreInhibited=no
#LidSwitchIgnoreInhibited=yes
#IdleAction=ignore
#IdleActionSec=30min
EOF

mv /etc/systemd/logind.conf.tmp /etc/systemd/logind.conf
