#!/usr/bin/zsh

let monitor_count="$(wlr-randr --json | jq 'length')"
(( monitor_count <= 1 )) && exit

# Wait for the socket
if ! [[ -S /run/user/1000/fr.emersion.kanshi.wayland-1 ]]; then
    printf 'Waiting for socket ' 1>&2
    let i=0
    while ! [[ -S /run/user/1000/fr.emersion.kanshi.wayland-1 ]]; do
        if (( i >= 20 )); then
            printf '\nFailed to connect to socket!\n' 1>&2
            exit 1
        fi
        i+=1
        printf '.' 1>&2
        sleep 0.1
    done
    printf '\n' 1>&2
fi

get_current_profile() {
    kanshictl status | jq -er '.current_profile'
}

let i=0
while ! get_current_profile >/dev/null; do
    if (( i >= 5 )); then
        break
    fi
    sleep 0.1
done

local current_profile="$(get_current_profile)"
local current_state="$(</proc/acpi/button/lid/LID0/state)"

if [[ "${current_profile}" = *open* ]] &&
       [[ "${current_state}" != *open* ]]; then
    kanshictl switch docked-closed
elif [[ "${current_profile}" = *closed* ]] &&
         [[ "${current_state}" != *closed* ]]; then
    kanshictl switch docked-open
fi
