#!/usr/bin/env bash

do_lock() {
  bg_file=$HOME/Desktop/background.png
  if test -f $bg_file && which i3lock-color >/dev/null 2>&1; then
    i3lock-color -i $bg_file "$@"
  else
    i3lock -c 777777 "$@"
  fi
}

xset +dpms dpms 10 10 10
revert_dpms() { xset dpms 0 0 0; }
trap revert_dpms EXIT

# We set a trap to kill the locker if we get killed, then start the locker and
# wait for it to exit. The waiting is not that straightforward when the locker
# forks, so we use this polling only if we have a sleep lock to deal with.
if [[ -e /dev/fd/${XSS_SLEEP_LOCK_FD:--1} ]]; then
    kill_i3lock() {
        pkill -xu $EUID "$@" i3lock
    }

    trap kill_i3lock TERM INT

    # we have to make sure the locker does not inherit a copy of the lock fd
    do_lock {XSS_SLEEP_LOCK_FD}<&-

    # now close our fd (only remaining copy) to indicate we're ready to sleep
    exec {XSS_SLEEP_LOCK_FD}<&-

    while kill_i3lock -0; do
        sleep 0.5
    done
else
    trap 'kill %%' TERM INT
    do_lock -n &
    wait
fi