#!/bin/bash

# omarchy:summary=Monitor sleep preparation and lock before suspend
# omarchy:group=system
# omarchy:hidden=true

consume_sleep_events() {
  local line sleep_lock
  sleep_lock="$OMARCHY_PATH/bin/omarchy-system-sleep-lock"

  while IFS= read -r line; do
    if [[ $line == *"boolean true"* ]]; then
      "$sleep_lock"
      return 0
    fi
  done
}

monitor_sleep_events() {
  local monitor_fd monitor_pid status

  coproc SLEEP_EVENTS {
    exec dbus-monitor --system \
      "type='signal',sender='org.freedesktop.login1',interface='org.freedesktop.login1.Manager',member='PrepareForSleep'"
  }
  monitor_fd=${SLEEP_EVENTS[0]}
  monitor_pid=$SLEEP_EVENTS_PID

  cleanup_monitor() {
    kill "$monitor_pid" 2>/dev/null || true
    wait "$monitor_pid" 2>/dev/null || true
  }
  trap cleanup_monitor EXIT

  consume_sleep_events <&"$monitor_fd"
  status=$?
  cleanup_monitor
  trap - EXIT

  return "$status"
}

case ${1:-} in
  --consume)
    consume_sleep_events
    exit 0
    ;;
  --inhibited)
    monitor_sleep_events
    exit 0
    ;;
esac

sleep_monitor="$OMARCHY_PATH/bin/omarchy-system-sleep-monitor"

exec systemd-inhibit \
  --what=sleep \
  --mode=delay \
  --who=Omarchy \
  --why="Lock screen before suspend" \
  "$sleep_monitor" --inhibited
