#!/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 "$(dirname "${LOCKFILE}")"
    exec 4<>"${LOCKFILE}"
    flock -n 4 || exit 0
    dunstctl set-paused true
    if has-rootful-xwayland-p; then
        swaylock ${empty_flag} --color '#000000'
    else
        swayidle -w -C /dev/null \
                 timeout 15 "${suspend_command}" resume "${wake_command}" &
        local swayidle_pid="${!}"
        swaylock ${empty_flag} ${img_flags}
        kill "${swayidle_pid}"
        eval "${wake_command}"
    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
            ;;
        -s)
            local suspend_command="${2}"
            shift
            ;;
        -w)
            local wake_command="${2}"
            shift
            ;;
        -e)
            empty_flag='-e'
            ;;
        -*)
            printf "error: unknown flag '%s'\n" "${1}" >&2
            ;;
    esac
    shift
done

if [[ -z "${suspend_command}" ]]; then
    # default to turning off all displays
    suspend_command="wlr-randr $(wlr-randr --json |
                         jq -r '[.[] | .modes = [.modes.[] |
                                select(.current)]] |
                                map("--output ''\(.name)'' --off") | join(" ")')"
fi

if [[ -z "${wake_command}" ]]; then
    wake_command="wlr-randr $(wlr-randr --json | jq -r '[.[]| select(.enabled) | .modes = [.modes.[] | select(.current)].[]] | map("--output ''\(.name)'' --on --mode ''\(.modes.width)x\(.modes.height)@\(.modes.refresh)Hz'' --pos ''\(.position.x),\(.position.y)'' --transform \(.transform) --scale \(.scale)") | join(" ")')"
fi

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

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