#!/bin/sh
# Dependencies:
#    dep-devuan: wmctrl, sudo
#    dep-el7: wmctrl, sudo
case "${1}" in
   help) # show this help screen
      {
         echo "Usage: ${0}: [command]"
         echo "used by logout-manager to perform actions like reboot, lock screen, etc."
         echo ""
         echo "Commands:"
         grep -E '^\s{3}[A-Za-z]+\)' "${0}" | tr -dc '[A-Za-z\n ]' | sed -r -e 's/\s+/ /g;' | grep -v "HIDDEN\s*$" | while read a therest ; do echo " ${a}: ${therest}" ; done
      }
      ;;
   options) # used by bash_completion function HIDDEN
      grep -E '^\s{3}[A-Za-z]+\)' "${0}" | awk '{print $1}' | tr -dc '[A-Za-z\n]' | grep -vE 'options|help'
      ;;
   lock) # lock the current screen
      if test -z "${DRYRUN}" ;
      then
         xscreensaver-command -lock
      else
         echo "xscreensaver-command -lock"
      fi
      ;;
   logout) # log out the current user of the graphical session
      # determine DE/WM and act accordingly
      _wm="$( wmctrl -m | awk '/Name:/{$1="";print;}' | xargs )"
      case "${_wm}" in
         Fluxbox)
            if test -z "${DRYRUN}" ;
            then
               fluxbox-remote exit
            else
               echo "fluxbox-remote exit"
            fi
            ;;
         *)
            echo "Gotta say unh! Feature not yet implemented for \"${_wm}\". Please report this to bgstack15@gmail.com" 1>&2
            exit 1
            ;;
      esac
      ;;
   hibernate) # save system state to disk and power off
      # this method is linux only
      if test -z "${DRYRUN}" ;
      then
         printf 'disk' | tee /sys/power/state
      else
         echo "printf 'disk' | tee /sys/power/state"
      fi
      ;;
   shutdown) # power off
      if test -z "${DRYRUN}" ;
      then
         shutdown -h now
      else
         echo "shutdown -h now"
      fi
      ;;
   reboot) # restart the system
      if test -z "${DRYRUN}" ;
      then
         shutdown -r now
      else
         echo "shutdown -r now"
      fi
      ;;
   *) # HIDE
      echo "invalid choice: ${1}" 1>&2
      exit 1
      ;;
esac
:
