#!/usr/bin/env bash

# omarchy:summary=Run the Omarchy screensaver using random effects from TTE.

screensaver_in_focus() {
  if "${BASH_SOURCE[0]%/*}/omarchy-on-hyprland"; then
    hyprctl activewindow -j | jq -e '.class == "org.omarchy.screensaver"' >/dev/null 2>&1
  else
    return 0
  fi
}

exit_screensaver() {
  if "${BASH_SOURCE[0]%/*}/omarchy-on-hyprland"; then
    hyprctl eval 'hl.config({ cursor = { invisible = false } })' &>/dev/null || hyprctl keyword cursor:invisible false &>/dev/null || true
  fi
  pkill -x ttfx 2>/dev/null
  pkill -f '[o]rg.omarchy.screensaver' 2>/dev/null
  exit 0
}

# Exit the screensaver on signals and input from keyboard and mouse
trap exit_screensaver SIGINT SIGTERM SIGHUP SIGQUIT

printf '\033]11;rgb:00/00/00\007'  # Set background color to black

if "${BASH_SOURCE[0]%/*}/omarchy-on-hyprland"; then
  hyprctl eval 'hl.config({ cursor = { invisible = true } })' &>/dev/null || hyprctl keyword cursor:invisible true &>/dev/null
fi

tty=$(tty 2>/dev/null)

# Terminals allocate the pty at the default 80x24 and only resize it once the
# compositor has told the window how big it is. ttfx measures the terminal once,
# at startup, so starting it before the resize lands sizes an 80x24 canvas and
# paints it into the corner of a fullscreen window.
wait_for_terminal_resize() {
  local deadline=$((SECONDS + 2))
  while ((SECONDS < deadline)) && [[ $(stty size 2>/dev/null) == "24 80" ]]; do
    sleep 0.02
  done
}

wait_for_terminal_resize

# Without the per-user copy, which a Debian install never makes, show the logo
# Restore Default would.
screensaver_text=~/.config/omarchy/branding/screensaver.txt
[[ -f $screensaver_text ]] || screensaver_text=${OMARCHY_PATH:-/usr/share/omarchy}/logo.txt

while true; do
  ttfx -i "$screensaver_text" \
    --frame-rate 120 --canvas-width 0 --canvas-height 0 --reuse-canvas --anchor-canvas c --anchor-text c\
    --random-effect --no-eol --no-restore-cursor &

  while pgrep -t "${tty#/dev/}" -x ttfx >/dev/null; do
    if read -n1 -t 1 || ! screensaver_in_focus; then
      exit_screensaver
    fi
  done
done
