#!/bin/bash

# omarchy:summary=Watch Hyprland monitor events and recover monitor toggles when a monitor is removed

SOCKET="$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE/.socket2.sock"

sync_clamshell() {
  omarchy-hyprland-monitor-clamshell
}

recover_after_monitor_removal() {
  sync_clamshell

  (
    sleep 1
    sync_clamshell
  ) &
}

sync_clamshell_after_monitor_change() {
  sync_clamshell

  (
    sleep 1
    sync_clamshell
  ) &
}

socat -U - "UNIX-CONNECT:$SOCKET" | while read -r event; do
  case "$event" in
    monitoradded\>\>*|monitoraddedv2\>\>*)
      sync_clamshell_after_monitor_change
      ;;
    monitorremoved\>\>*|monitorremovedv2\>\>*)
      recover_after_monitor_removal
      ;;
  esac
done
