#!/usr/bin/env zsh

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

function has-rootful-xwayland-p {
    for pid in $(pgrep Xwayland); do
        local cmdline=(${(0)"$(cat /proc/"${pid}"/cmdline)"})
        if ! ((${cmdline[(Ie)-rootless]})); then
            return 0
        fi
    done
    return 1
}

function run {
    # ensure multiple instances do not run
    mkdir -p "${LOCKFILE:h}"
    exec 4<>"${LOCKFILE}"
    flock -n 4 || exit 0
    dunstctl set-paused true
    if [[ "${XDG_CURRENT_DESKTOP}" == 'river' ]] && has-rootful-xwayland-p; then
        swaylock ${empty_flag} --color '#000000'
    else
        # get the list of currently disabled monitors so we don't touch them
        local ignored=("${(0)$(enable-displays-for-sleep -l)}")
        local ignored_args=()
        for name in ${ignored}; do
            # quote so it can be safely passed to swayidle
            ignored_args+=(-i "${(q)name}")
        done

        swayidle -w -C /dev/null \
                 timeout 15 "enable-displays-for-sleep -d ${ignored}" \
                 resume "enable-displays-for-sleep {$ignored}" &
        local swayidle_pid="${!}"
        swaylock ${empty_flag} ${img_flags}
        kill "${swayidle_pid}"
    fi
    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=''
local wake_command=''
local empty_flag=''
local fix_eww=()
while [[ "${1}" =~ '^-' ]]; do
    case "${1}" in
        --)
            shift
            break
            ;;
        -f)
            background=true
            ;;
        -b)
            fix_eww+="${2}"
            shift
            ;;
        -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
