#!/usr/bin/env zsh

pidfile=${XDG_RUNTIME_DIR-/run/user/$UID}/xscreensaver-companion.pid
trap "rm -f $pidfile" INT KILL

function check_start
{
    # check if the service is running and, if not, start it in the background
    # and detach
    if pgrep -u $USER $1 >/dev/null; then
        return 0
    else
        $* &>/dev/null </dev/null & disown
    fi
}

function init_pidfile
{
    local pid
    if read pid < $pidfile; then
        if kill -0 $pid; then
            echo 'I am already running!' >&2
            exit 1
        else
            echo 'Remove stale lock file.' >&2
            rm $pidfile
        fi
    fi
    echo $$ > $pidfile
}

function parse_actions
{
    while read action _; do
        case $action in
            (LOCK|BLANK)
                setxkbmap us -option
                dunstctl set-paused true
                ;;
            (UNBLANK)
                check_start gxkb
                $HOME/git/mine/vscripts/mykblayouts
                $HOME/.local/bin/touchpad-config
                dunstctl set-paused false
                ;;
        esac
    done
}

init_pidfile
xscreensaver-command -watch | parse_actions