#!/usr/bin/env zsh

LOCKFILE="${HOME}/.cache/swayidle-lock-screen.lock"
ENABLE_DISPLAYS="${HOME}/scripts/enable-displays-for-sleep"
RESET_SAFEEYES="${HOME}/scripts/reset-safeeyes-time"

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 safeeyes-running-p {
    [[ "$(safeeyes --status)" = Next* ]]
}

function run {
    # ensure multiple instances do not run
    mkdir -p "${LOCKFILE:h}"
    exec 4<>"${LOCKFILE}"
    flock -n 4 || exit 0
    dunstctl set-paused true
    let need_restore_safeeyes=0
    if safeeyes-running-p; then
        safeeyes --disable
        need_restore_safeeyes=1
    fi
    if [[ "${XDG_CURRENT_DESKTOP}" == 'river' ]] && has-rootful-xwayland-p; then
        swaylock ${empty_flag} --color '#000000'
    else
        local swayidle_pid
        if ((dont_sleep)); then
            # get the list of currently disabled monitors so we don't touch them
            local ignored=("${(0)$("${ENABLE_DISPLAYS}" -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 "${(q)ENABLE_DISPLAYS} -d ${ignored_args}" \
                     resume "${(q)ENABLE_DISPLAYS} {$ignored_args}" &
            swayidle_pid="${!}"
        else
            swayidle -w -C /dev/null \
                     timeout 15 "systemctl sleep" &
            swayidle_pid="${!}"
        fi
        swaylock ${empty_flag} ${img_flags}
        kill "${swayidle_pid}"
    fi
    (( need_restore_safeeyes )) && safeeyes --enable
    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=()
let dont_sleep=0
while [[ "${1}" =~ '^-' ]]; do
    case "${1}" in
        --)
            shift
            break
            ;;
        -f)
            background=true
            ;;
        -b)
            fix_eww+="${2}"
            shift
            ;;
        -e)
            empty_flag='-e'
            ;;
        -d)
            dont_sleep=1
            ;;
        -*)
            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
