#!/bin/sh
#
#  xfce4
#
#  Copyright (C) 1999, 2003 Olivier Fourdan (fourdan@xfce.org)
#  Copyright (C) 2011       Guido Berhoerster (guido+xfce.org@berhoerster.name)
#  Copyright (C) 2011, 2020 Jarno Suni (8@iki.fi)
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
unset -v IFS

# First test for the command set in the session's xfconf channel.
LOCK_CMD=$(xfconf-query -c xfce4-session -p /general/LockCommand)

# Try using the lock command. If it fails, try locking by a known
# screensaver which requires its daemon running.
for lock_cmd in \
	"${LOCK_CMD:-false}" \
	'xfce4-screensaver-command --lock' \
	'light-locker-command --lock' \
	'xscreensaver-command -lock' \
	'mate-screensaver-command --lock' \
	'cinnamon-screensaver-command --lock' \
	'gnome-screensaver-command --lock'
do
	$lock_cmd >/dev/null 2>&1 && exit
done

# function: wrap locker command so that display power management
# signaling (DPMD) can be applied. Restore old settings when unlocking.
# Give the command and its options as parameters. 
command_dpms() {
	revert() {
		xset dpms ${xstate}dpms
		exit
	}
	trap revert TERM HUP
	# Save the state of DPMS; rely on the output format of `xset q`.
	xstate=$(xset q | awk '/^DPMS /{getline; printf "%s %s %s ", $2, $4, $6;
		getline; if($3=="Enabled"){print "+"}else{print "-"}exit}')
	# Enable monitor power management with some timeouts
	xset dpms 10 15 20
	$*
	revert
}

# function: turn off display almost immediately
inital_dpms() {
	sleep 1
	xset dpms force off
}

# Run another access locking utility, if installed.
# These fallback lockers do not fork.
for lock_cmd in \
	'xlock -mode blank' \
	'i3lock --nofork' \
	'xtrlock -b' \
	'alock' \
	'slock'
do
	set -- $lock_cmd
	if command -v -- "$1" >/dev/null 2>&1; then
		command_dpms $lock_cmd &
		inital_dpms &
		exit 0
	fi
done

# else access locking failed
exit 1
