#!/usr/bin/zsh

# Only run on laptops
[[ "${HOST}" = *-portable ]] || exit 0

# 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
        sleep 0.1
        printf '.' 1>&2
    done
    printf '\n' 1>&2
fi

get_current_profile() {
    local profile
    profile="${$(kanshictl status):17}"
    (( $? )) && return 1
    : ${(P)1::="${profile}"}
}

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

local monitor_count_str="$(wlr-randr --json | jq 'length')"
[[ "${monitor_count_str}" =~ '[0-9]+' ]] || exit
let monitor_count="${monitor_count_str}"
(( monitor_count <= 1 )) && [[ "${current_profile}" != 'default' ]] \
    && kanshictl switch default

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
