#!/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, 2016, 2017 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.
#
set -eu
export PATH=/usr/local/bin:$(command -p getconf PATH)
# Note that adding :/usr/local/bin explicitly is not needed here, except
# maybe for testing, or if you want to allow locally build software.

# Lock by a known screensaver, if its daemon is running
for lock_cmd in \
  "light-locker" \
  "mate-screensaver" \
  "cinnamon-screensaver" \
  "gnome-screensaver"
do
  lock_cmd=${lock_cmd}-command
  [ -n "$($lock_cmd --query 2>/dev/null)" ] &&
   $lock_cmd --lock &&
    exit
done
for lock_cmd in \
    "xscreensaver-command -lock"
do
  $lock_cmd >/dev/null 2>&1 && exit
done

# else run another access locking utility, if installed.
# These commands do not fork.
for lock_cmd in \
  "i3lock --nofork" \
  "xtrlock -b" \
  "slock" \
  "slimlock" \
  "alock -bg blank -auth pam" \
  "xlock -mode blank"
  do
    set -- $lock_cmd
    if command -v -- $1 >/dev/null 2>&1; then
        command-dpms $lock_cmd &
        PID=$!
        # Test, if the command is running after small delay;
        # The command may have exited e.g. due to invalid command line
        # arguments; e.g. -b option does not work with an old version
        # of xtrlock.
        sleep 0.1
        kill -0 "$PID" 2>/dev/null || continue
        exit
    fi
done

# else access locking failed
exit 1
