#!/bin/sh

fetchjoke() {
    curl -sH "Accept: text/plain" https://icanhazdadjoke.com/ |
        sed 's/\? /\?\n/' | sed 's/\. /\.\n/' >~/.cache/dadjoke
}

if iconf -i dadjoke; then
    # fetch random dad joke
    if ! [ -e ~/.cache/dadjoke ]; then
        fetchjoke
    fi
    (sleep 2 && fetchjoke &)

    MESSAGE="$(cat ~/.cache/dadjoke)"
elif [ "$1" = "message" ]; then
    # manual message
    MESSAGE="$(imenu -i "enter lock screen message")"
    [ -z "$MESSAGE" ] && exit
    shift
else
    # default
    MESSAGE="locked, enter password for $(whoami)"
fi

if [ "$1" = '-o' ] || [ -n "$ILOCKACTIVE" ]; then
    if iconf -i nolocktimeout; then
        echo "keeping screen active"
        instantlock -o -d
    else
        instantlock -o && xset -dpms
    fi
else
    if ! iconf -i nolocktimeout; then
        instantlock -m "${@:-$MESSAGE}" && xset -dpms
    else
        echo "keeping screen active"
        instantlock -d -m "${@:-$MESSAGE}"
    fi
fi
