#!/bin/bash

# dmenuxautolock
#
# Provides a dmenu for configuring the lock timeout and notification duration
# for xautolock - a utility which triggers screen lock - in this case using
# 'loginctl lock-session'.

SCRIPT_NAME="$(basename -- "$0")"
FILE="/tmp/dmenuxautolock"
DEFAULT_TIMEOUT=1
DEFAULT_NOTIFY=10
TIMEOUT=0
NOTIFY=0

function usage() {
    echo "Usage: $SCRIPT_NAME [OPTIONS]"
    echo
    echo "Options:"
    echo "  -h          Display help."
    echo "  -t [MIN]    Time after which to lock the screen."
    echo "  -n [SEC]    Notify n seconds before locking."
}

while getopts ":t:n:h" arg; do
    case $arg in
    t) TIMEOUT=$OPTARG ;;
    n) NOTIFY=$OPTARG ;;
    h)
        usage
        exit 0
        ;;
    :)
        echo "$SCRIPT_NAME: Must supply an argument to -$OPTARG." >&2
        usage
        exit 1
        ;;
    ?)
        echo "Invalid option: -${OPTARG}."
        echo
        usage
        exit 2
        ;;
    esac
done

function read_current() {
    local timeout notify

    timeout="$(cut -d, -f1 2>/dev/null <"$FILE")"
    notify="$(cut -d, -f2 2>/dev/null <"$FILE")"

    [ -n "$timeout" ] && export CURRENT_TIMEOUT="$timeout"
    [ -n "$notify" ] && export CURRENT_NOTIFY="$notify"
}
read_current

if [ -z "$TIMEOUT" ]; then
    [ -n "$CURRENT_TIMEOUT" ] && TIMEOUT="$CURRENT_TIMEOUT" || TIMEOUT="$DEFAULT_TIMEOUT"
fi

if [ "$TIMEOUT" -eq 0 ]; then
    [ -n "$CURRENT_TIMEOUT" ] && current="$CURRENT_TIMEOUT" || current="$DEFAULT_TIMEOUT"
    timeout="$(xargs -n 1 <<<"'$current min (current)' '1 min' '2 min' '5 min' '15 min' '30 min' '60 min'" | dmenu -i -l 25 -p "Lock timeout")"
    TIMEOUT="$(cut -d' ' -f1 <<<"$timeout")"
    [ -z "$TIMEOUT" ] && exit 1
fi

if [ -z "$NOTIFY" ]; then
    [ -n "$CURRENT_NOTIFY" ] && NOTIFY="$CURRENT_NOTIFY" || NOTIFY="$DEFAULT_NOTIFY"
fi

if [ "$NOTIFY" -eq 0 ]; then
    [ -n "$CURRENT_NOTIFY" ] && current="$CURRENT_NOTIFY" || current="$DEFAULT_NOTIFY"
    notify="$(xargs -n 1 <<<"'$current sec (current)' '15 sec' '30 sec' '45 sec'" | dmenu -i -l 25 -p "Lock notify")"
    NOTIFY="$(cut -d' ' -f1 <<<"$notify")"
    [ -z "$NOTIFY" ] && exit 1
fi

echo "INFO: Setting TIMEOUT=$TIMEOUT, NOTIFY=$NOTIFY."
echo "$TIMEOUT,$NOTIFY" >"$FILE"

killall xautolock 2>/dev/null
xautolock -time "$TIMEOUT" -locker 'loginctl lock-session' -notify "$NOTIFY" -notifier "notify-send --expire-time $((NOTIFY * 1000)) --icon=gtk-info xautolock 'The screen will lock soon.'" &
xalpid=$!
sleep 0.5

if ! [ -d "/proc/${xalpid}" ]; then
    i3-nagbar -m 'Error: xautolock failed to start!' &
fi
