#!/usr/bin/env zsh

LOCKFILE="${HOME}/.cache/swayidle-lock-screen.lock"

function run {
    # ensure multiple instances do not run
    mkdir -p "$(dirname "${LOCKFILE}")"
    exec 4<>"${LOCKFILE}"
    flock -n 4 || exit 0
    dunstctl set-paused true
    swayidle -w -C /dev/null \
        timeout 15 "${suspend_command}" resume "${wake_command}" &
    local swayidle_pid="${!}"
    swaylock ${empty_flag} ${img_flags}
    kill "${swayidle_pid}"
    hyprctl dispatch dpms on
    dunstctl set-paused false
    fix_eww
    flock -u 4
}

function fix_eww {
    if (( ${#fix_eww} > 0 )); then
        eww open-many ${fix_eww}
    fi
}

local background=false
local suspend_command='hyprctl dispatch dpms off'
local wake_command='hyprctl dispatch dpms on'
local empty_flag=''
local fix_eww=()
while [[ "${1}" =~ '^-' ]]; do
    case "${1}" in
        --)
            shift
            break
            ;;
        -f)
            background=true
            ;;
        -b)
            fix_eww+="${2}"
            shift
            ;;
        -s)
            local suspend_command='sudo /usr/lib/systemd/systemd-sleep suspend &'
            ;;
        -e)
            empty_flag='-e'
            ;;
        -*)
            printf "error: unknown flag '%s'\n" "${1}" >&2
            ;;
    esac
    shift
done

(( ${#} != 0 )) && img_flags=(-s fill -i "${1}")

if ${background}; then
    run '${img_flags}' &
else
    run '${img_flags}'
fi