#!/bin/bash

# omarchy:summary=Watch Hyprland monitor events and reconcile clamshell display state
# omarchy:hidden=true

is_pgid_leader() {
  local stat="" pgrp=""
  read -r stat 2>/dev/null </proc/$$/stat || return 1
  stat=${stat##*) }
  read -r _ _ pgrp _ <<<"$stat"
  [[ $pgrp =~ ^[0-9]+$ ]] && (( pgrp == $$ ))
}

# Lead our own process group in-place (preserving PID and cgroup) so shutdown
# stops every worker and stuck helper atomically with `kill -- -$$`, even when
# launched in a shared process group (uwsm-app).
if ! is_pgid_leader && [[ -z ${OMARCHY_MONITOR_WATCH_PGID:-} ]] && command -v setsid >/dev/null 2>&1; then
  exec env OMARCHY_MONITOR_WATCH_PGID=1 setsid "$0" "$@"
fi
unset OMARCHY_MONITOR_WATCH_PGID

SOCKET="$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE/.socket2.sock"
LOCK="${XDG_RUNTIME_DIR:-/tmp}/omarchy-monitor-clamshell.lock"
MODELESS_LOCK="${XDG_RUNTIME_DIR:-/tmp}/omarchy-monitor-modeless.lock"
BACKSTOP_SECONDS="${OMARCHY_CLAMSHELL_BACKSTOP_SECONDS:-60}"
[[ $BACKSTOP_SECONDS =~ ^[1-9][0-9]*$ ]] || BACKSTOP_SECONDS=60
socket_fd=""

close_fds() {
  if [[ -n ${logind_fd:-} ]]; then
    { exec {logind_fd}<&-; } 2>/dev/null || true
    logind_fd=""
  fi
  if [[ -n ${socket_fd:-} ]]; then
    { exec {socket_fd}<&-; } 2>/dev/null || true
    socket_fd=""
  fi
}

# Retry wait when interrupted by a trapped signal (rc > 128), e.g. the
# self-delivered SIGTERM from `kill -- -$pgid` during group cleanup.
reap_children() {
  local wrc
  while true; do
    wrc=0
    wait 2>/dev/null || wrc=$?
    (( wrc > 128 )) || break
  done
}

sync_clamshell() {
  (
    flock -n 9 || exit 1
    omarchy-hyprland-monitor-clamshell 9>&-
    omarchy-system-lid-inhibit 9>&-
    exit 0
  ) 9>"$LOCK"
}

retry_clamshell_sync() {
  local immediate="${1:-0}"
  (
    close_fds
    local ran=0
    (( immediate )) && sync_clamshell && ran=1
    for delay in 1 3 7; do
      sleep "$delay"
      sync_clamshell && ran=1
    done
    # If $LOCK stayed busy through every hotplug retry, keep one coalesced
    # waiter so undock recovery and inhibitor release cannot be dropped.
    if (( immediate && ! ran )); then
      (
        flock -n 8 || exit 0
        flock 9
        exec 8>&-
        omarchy-hyprland-monitor-clamshell 9>&-
        omarchy-system-lid-inhibit 9>&-
      ) 8>"$LOCK.wait" 9>"$LOCK"
    fi
  ) &
}

sync_clamshell_after_monitor_change() {
  retry_clamshell_sync 1
}

# Powering the monitor on fires no DRM hotplug, and forcing a re-probe needs
# root, so only a reload re-reads the EDID and only a reload reveals whether it
# worked. Back off: the machine can sit like this all night. The lock keeps one
# loop running across the events that call this; the wait is for an event landing
# in the moment one is exiting, which would otherwise be the last one to come.
recover_modeless() {
  (
    close_fds
    flock -w 1 9 || exit 0

    local delay=3 state reloaded unanswered=0

    while true; do
      omarchy-hyprland-monitor-modeless 9>&-
      state=$?

      # A monitor reporting a mode is recovered. One the compositor cannot speak
      # for is not an answer, and nothing else will ask again -- but a compositor
      # that stays silent has gone, taking the session and this loop's reason
      # with it.
      (( state == 1 )) && break
      (( state == 2 )) && (( ++unanswered > 20 )) && break
      (( state == 0 )) && unanswered=0

      reloaded=0
      # Reloading into half-replaced package config is what the guard prevents.
      if (( state == 0 )) && ! omarchy-hyprland-reload-guard paused 9>&-; then
        omarchy-restart-hyprctl 9>&-
        reloaded=1
      fi

      sleep "$delay" 9>&-
      (( reloaded )) && (( delay = delay * 2 > 60 ? 60 : delay * 2 ))
    done
  ) 9>"$MODELESS_LOCK" &
}

read_monotonic_seconds() {
  local up=""
  read -r up _ </proc/uptime
  now=${up%%.*}
}

# Watch systemd-logind for lid transitions, suspend resume, and logind restarts
# instead of polling every 2s. Runs in its own process group (via `set -m`) so
# undock and shutdown stop gdbus and any in-flight retry workers atomically.
watch_logind_events() {
  set +m
  close_fds
  local line owner="" new_owner gdbus_pid="" logind_fd="" backoff=1 reconnecting=0
  local now next_sync remaining rc

  trap 'trap : TERM INT; kill -- -"$BASHPID" 2>/dev/null || true; reap_children; exit 0' TERM INT

  read_monotonic_seconds
  next_sync=$(( now + BACKSTOP_SECONDS ))

  while true; do
    owner=""
    exec {logind_fd}< <(exec env LC_ALL=C gdbus monitor --system --dest org.freedesktop.login1 --object-path /org/freedesktop/login1 2>/dev/null)
    gdbus_pid=$!

    if (( reconnecting )); then
      ( close_fds; sync_clamshell ) &
      read_monotonic_seconds
      next_sync=$(( now + BACKSTOP_SECONDS ))
    fi

    while true; do
      read_monotonic_seconds
      remaining=$(( next_sync - now ))
      if (( remaining <= 0 )); then
        ( close_fds; sync_clamshell ) &
        next_sync=$(( now + BACKSTOP_SECONDS ))
        remaining=$BACKSTOP_SECONDS
      fi

      rc=0
      IFS= read -t "$remaining" -r -u "$logind_fd" line || rc=$?

      if (( rc == 0 )); then
        case "$line" in
          *"org.freedesktop.DBus.Properties.PropertiesChanged"*"'LidClosed'"* | \
          *"org.freedesktop.login1.Manager.PrepareForSleep (false,"*)
            backoff=1
            read_monotonic_seconds
            next_sync=$(( now + BACKSTOP_SECONDS ))
            retry_clamshell_sync
            ;;
          "The name org.freedesktop.login1 is owned by "*)
            backoff=1
            new_owner=${line##* }
            if (( reconnecting )) || [[ -n $owner && $new_owner != $owner ]]; then
              reconnecting=0
              read_monotonic_seconds
              next_sync=$(( now + BACKSTOP_SECONDS ))
              retry_clamshell_sync
            fi
            owner=$new_owner
            ;;
        esac
      elif (( rc <= 128 )); then
        break
      fi
    done

    kill "$gdbus_pid" 2>/dev/null || true
    wait "$gdbus_pid" 2>/dev/null || true
    { exec {logind_fd}<&-; } 2>/dev/null || true
    logind_fd=""
    reconnecting=1

    sleep "$backoff"
    (( backoff = backoff * 2 > 60 ? 60 : backoff * 2 ))
  done
}

# The internal panel is only ever disabled while a laptop is docked (lid shut
# with an external monitor active), so only watch logind while an external
# display is active, stop it when Hyprland confirms none is active (exit 1),
# and never run it on a machine without a lid. When Hyprland cannot answer
# (exit 2, e.g. mid-reload), keep an existing watcher running, fall back to
# physical DRM connectors if none is running yet, and recheck on configreloaded.
logind_watch_pid=""
logind_watch_recheck=0
logind_recheck_at=0

logind_watch_running() {
  [[ -n $logind_watch_pid ]] || return 1
  local stat="" st="" ppid=""
  read -r stat 2>/dev/null </proc/"$logind_watch_pid"/stat || return 1
  stat=${stat##*) }
  read -r st ppid _ <<<"$stat"
  [[ $st != "Z" && $st != "X" && $ppid =~ ^[0-9]+$ ]] && (( ppid == $$ ))
}

start_logind_watch() {
  if ! logind_watch_running; then
    [[ -n $logind_watch_pid ]] && wait "$logind_watch_pid" 2>/dev/null || true
    local term_pending=0
    trap 'term_pending=1' TERM INT
    set -m
    watch_logind_events </dev/null &
    logind_watch_pid=$!
    set +m
    trap 'cleanup_main; exit 0' TERM INT
    (( term_pending )) && { cleanup_main; exit 0; }
  fi
}

stop_logind_watch() {
  if [[ -n $logind_watch_pid ]]; then
    logind_watch_running && kill -- -"$logind_watch_pid" 2>/dev/null || true
    wait "$logind_watch_pid" 2>/dev/null || true
    logind_watch_pid=""
  fi
}

sync_logind_watch() {
  if ! omarchy-hw-laptop; then
    logind_watch_recheck=0
    stop_logind_watch
    return
  fi

  local state=0
  omarchy-hyprland-monitor-external-active || state=$?

  case $state in
    0)
      local rechecked=$logind_watch_recheck
      logind_watch_recheck=0
      start_logind_watch
      if (( rechecked )); then retry_clamshell_sync; fi
      ;;
    1)
      local rechecked=$logind_watch_recheck
      logind_watch_recheck=0
      stop_logind_watch
      if (( rechecked )); then sync_clamshell_after_monitor_change; fi
      ;;
    *)
      if (( ! logind_watch_recheck )); then
        local now
        read_monotonic_seconds
        logind_recheck_at=$(( now + BACKSTOP_SECONDS ))
      fi
      logind_watch_recheck=1
      omarchy-hw-external-monitors && start_logind_watch
      ;;
  esac
}

main_exiting=0
cleanup_main() {
  trap : TERM INT
  (( main_exiting )) && return 0
  main_exiting=1
  stop_logind_watch
  if is_pgid_leader; then
    kill -- -"$$" 2>/dev/null || true
  else
    pkill -P "$$" 2>/dev/null || true
  fi
  reap_children
}

trap 'cleanup_main; exit 0' TERM INT
trap 'cleanup_main' EXIT

exec {socket_fd}< <(exec socat -U - "UNIX-CONNECT:$SOCKET")

sync_clamshell_after_monitor_change
sync_logind_watch
recover_modeless

while true; do
  rc=0
  if (( logind_watch_recheck )); then
    read_monotonic_seconds
    remaining=$(( logind_recheck_at - now ))
    if (( remaining <= 0 )); then
      logind_recheck_at=$(( now + BACKSTOP_SECONDS ))
      sync_logind_watch
      continue
    fi
    read -t "$remaining" -r -u "$socket_fd" event || rc=$?
  else
    read -r -u "$socket_fd" event || rc=$?
  fi

  if (( rc > 128 )); then
    if (( logind_watch_recheck )); then
      read_monotonic_seconds
      logind_recheck_at=$(( now + BACKSTOP_SECONDS ))
      sync_logind_watch
    fi
    continue
  elif (( rc != 0 )); then
    break
  fi

  case "$event" in
    monitoradded\>\>*|monitoraddedv2\>\>*|monitorremoved\>\>*|monitorremovedv2\>\>*)
      sync_clamshell_after_monitor_change
      sync_logind_watch
      recover_modeless
      ;;
    # A reload while the monitor is unpowered leaves it at 0x0 with no hotplug
    # to notice, same as at boot. Our own recovery reload lands here too, and is
    # a no-op while its loop still holds the pid.
    configreloaded\>\>*)
      recover_modeless
      (( logind_watch_recheck )) && sync_logind_watch
      ;;
  esac
done
