#!/bin/sh
# File: xscreensaver-watch
# License: CC-BY-SA 4.0
# Author: bgstack15
# Startdate: 2020-03-23 07:25
# Title: Script that Triggers Actions based on Xscreensaver Status
# Purpose: make a daemon that watches xscreensaver and connects to wired network upon screen unlock.
# History:
# Usage:
#    place xscreensaver-watch in your startup scripts. Set the $XSW_PATH or alternatively $PATH with order of precedence for the `on-xsw-lock` and `on-xsw-unblanked` commands.
# References:
#    https://bbs.archlinux.org/viewtopic.php?pid=1182514
#    wicd-cli -z -c
#    alternative: https://www.jwz.org/xscreensaver/faq.html#watch xscreensaver-command -watch
#    man xscreensaver-command
# Improve:
# Dependencies:
#    dep-raw: xscreensaver-command, lecho
#    rec-devuan: xscreensaver, bgscripts-core

test -e "/etc/sysconfig/xscreensaver-watch" && . /etc/sysconfig/xscreensaver-watch
test -e "/etc/default/xscreensaver-watch" && . /etc/default/xscreensaver-watch
test -z "${XSW_KILLFILE}" && XSW_KILLFILE=/tmp/kill-xscreensaver-watch.tmp
test -z "${XSW_LOGFILE}" && XSW_LOGFILE=~/log/xsw.log
test -n "${XSW_PATH}" && export PATH="${XSW_PATH}:${PATH}"
test -d "$( dirname "${XSW_LOGFILE}" )" && mkdir -p "$( dirname "${XSW_LOGFILE}" )"

# Functions
log() {
   /usr/bin/lecho "${*}" | tee -a "${XSW_LOGFILE}" 1>&2
}

clean_xsw() {
   rm "${XSW_KILLFILE}"
   exit 0
}

on_locked() {
   log "invoking on-xsw-locked"
   on-xsw-locked
}

on_unblanked() {
   log "invoking on-xsw-unblanked"
   on-xsw-unblanked
}

# INITIALIZATION
trap 'trap "" 2 10 ; clean_xsw ;' 2 10 # CTRL-C SIGUSR1

# MAIN
rm "${XSW_KILLFILE}" 2>/dev/null
XSW_status=0
xscreensaver-command -watch | \
while read line ;
do
   test -e "${XSW_KILLFILE}" && clean_xsw
   case "$( echo "${line}" | grep -oE '^LOCK|UNBLANK' )" in
      "LOCK")
         XSW_status=locked
         ;;
      "UNBLANK")
         XSW_status=unblanked
         ;;
   esac
   if test "${XSW_status}" != "${XSW_oldstatus}" ;
   then
      on_${XSW_status}
   fi
   XSW_oldstatus="${XSW_status}"
   sleep 1
done
echo "${0}: xscreensaver-command terminated, so I am also stopping."

# exit safely if for some reason xscreensaver-command ended
trap '' 2 10
clean_xsw
