#!/bin/bash

LID_STATE_FILE="/proc/acpi/button/lid/LID/state"
DOCK_MONITOR="DP-3"
LAPTOP_MONITOR="eDP-1"

find_hypr_socket() {
    local runtime_dir
    runtime_dir="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
    for d in "$runtime_dir"/hypr/*/; do
        if [[ -S "${d}.socket.sock" ]]; then
            echo "$(basename "$d")"
            return 0
        fi
    done
    return 1
}

ensure_hyprctl() {
    if ! command -v hyprctl &>/dev/null; then
        return 1
    fi
    if [[ -z "$HYPRLAND_INSTANCE_SIGNATURE" ]]; then
        local sig
        sig=$(find_hypr_socket)
        if [[ -n "$sig" ]]; then
            export HYPRLAND_INSTANCE_SIGNATURE="$sig"
            export HYPRLAND_INSTANCE_SIGNATURE="$sig"
        else
            return 1
        fi
    fi
    return 0
}

hyprctl_wait() {
    while ! ensure_hyprctl; do
        sleep 1
    done
}

is_docked() {
    hyprctl monitors 2>/dev/null | grep -q "^Monitor $DOCK_MONITOR"
}

move_workspaces_to_dock() {
    local workspaces
    workspaces=$(hyprctl workspaces 2>/dev/null | grep -B1 "monitor: $LAPTOP_MONITOR" | grep "^workspace ID" | awk '{print $3}')
    for ws in $workspaces; do
        hyprctl dispatch moveworkspacetomonitor "$ws" "$DOCK_MONITOR" >/dev/null 2>&1
    done
}

hyprctl_wait

prev_state=""
while true; do
    if [[ -f "$LID_STATE_FILE" ]]; then
        state=$(awk '{print $2}' < "$LID_STATE_FILE")
    else
        state="unknown"
    fi

    if [[ "$state" != "$prev_state" ]]; then
        if [[ "$state" == "closed" ]] && is_docked; then
            move_workspaces_to_dock
            hyprctl keyword monitor "$LAPTOP_MONITOR,disable" >/dev/null 2>&1
        elif [[ "$state" == "open" ]]; then
            hyprctl keyword monitor "$LAPTOP_MONITOR,preferred,auto,1" >/dev/null 2>&1
        fi
        prev_state="$state"
    fi
    sleep 1
done
