#!/bin/sh

COPYRIGHT="
Copyright (C) 2017 by Intevation GmbH
Author(s):
Thomas Arendsen Hein <thomas@intevation.de>

This program is free software under the GNU GPL (>=v2)
"

LOCKTIME=10 # minutes
NOTIFY=10   # seconds

NOTIFY_MSECS="$(( $NOTIFY * 1000 ))" # milliseconds
DPMSSUSPEND="$(( $LOCKTIME * 60 ))" # seconds
DPMSOFF_MINS="$(( $LOCKTIME * 2 ))" # minutes
DPMSOFF="$(( $DPMSOFF_MINS * 60 ))" # seconds

SLOCK="slock"

SETUP="
  xset s 0 0 dpms 0 0 0
  xautolock -time $LOCKTIME -locker \"$0\" -corners \"----\" \\
            -notify $NOTIFY -notifier \"notify-send -u low -t $NOTIFY_MSECS \\
            'screen locks in $NOTIFY seconds'\" &
"

usage() {
    cat << EOF
Usage: $(basename $0) [option]

Wrapper script for $SLOCK, automatic locking (with xautolock)
and DPMS setup (with xset).

Options:
  --help    display this help and exit
  --setup   perform the setup steps for xautolock and DPMS
            as shown in the section SETUP below.

Other options are ignored to be able to use this script as a drop-in
replacement for e.g. "xlock -remote". This may change in future versions.


DESCRIPTION
-----------

- manually lock your screen by running this script without options
- disable DPMS when not locked, so a black screen means: locked
- lock with DPMS standby after $LOCKTIME minutes inactivity
- disable automatic locking when the mouse pointer is in a window corner
- notification $NOTIFY seconds before locking due to inactivity
- immediate DPMS standby after (manual or automatic) locking
- when locked:
  - enter DPMS standby after 1 minute of inactivity
  - enter DPMS suspend after $LOCKTIME minutes inactivity
  - enter DPMS off after $DPMSOFF_MINS minutes inactivity


SETUP
-----

Add "$0 --setup" to your \$HOME/.xsession script.
This will run the following commands:
$SETUP
If you want to change options without modifying this script, you can
directly add above commands to your .xsession script.

It is recommended to configure a hotkey to call this script for manual
locking. Or rename/symlink this script to "xlock", if your window manager
already has a hotkey for calling it.


COPYRIGHT
---------
$COPYRIGHT
EOF
}

if [ "$1" = "--help" ]; then
    usage
    exit 0
elif [ "$1" = "--setup" ]; then
    eval "$SETUP"
else
    # do not restore setup values if locking failed, e.g. because the screen is
    # already locked, but do this if slock was killed (exit code > 128)
    "$SLOCK" xset dpms 60 $DPMSSUSPEND $DPMSOFF dpms force standby
    rc="$?"
    if [ "$rc" -eq 0 -o "$rc" -gt 128 ]; then
        xset dpms 0 0 0
    fi
    exit "$rc"
fi
