#!/bin/bash

# omarchy:summary=Launch the Omarchy shell with its log kept in the journal
# omarchy:hidden=true

# Quickshell only logs to its instance runtime dir (tmpfs), so when the shell
# dies the idle/lock event trail is gone after a reboot. The journal keeps it
# across sessions, bounded and timestamped, under the omarchy-shell tag.
#
# Backgrounded because bash defers a trap until a foreground command returns but
# interrupts wait. systemd-cat execs, so the job is Quickshell itself.
#
# Quickshell's own reloading is off; Omarchy restarts the shell deliberately.
# A package upgrade rewriting $OMARCHY_PATH/shell would otherwise reload it
# against a half-written tree, and that failed reload leaves a second engine
# generation behind that turns the next restart's IPC kill into a crash.
#
# Quickshell's crash handler is off too. It opens a report dialog that takes
# focus after every crash, after the shell is already back, so a key typed at
# that moment lands on "Open report page". The relaunch below covers what the
# handler did, and systemd-coredump with omarchy-crash-watch reports the crash.
#
# Quickshell links libjemalloc.so.2, whose default 4*ncpu arenas, 10s decay,
# and THP-backed 4 MiB extents hold ~110 MiB of fragmented/idle heap on a
# 16 GiB laptop. Constraining arenas, decay, and THP keeps idle RSS tight;
# Util.execDetached/execArgv scrub MALLOC_CONF so launched apps don't inherit it.
run_shell() {
  local startup_background
  startup_background=$(readlink -f "$HOME/.local/state/omarchy/current/background" 2>/dev/null)
  OMARCHY_STARTUP_BACKGROUND="$startup_background" \
    MALLOC_CONF="${MALLOC_CONF:-narenas:2,tcache_max:4096,background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:0,thp:never}" \
    QS_DISABLE_FILE_WATCHER=1 QS_NO_RELOAD_POPUP=1 QS_DISABLE_CRASH_HANDLER=1 \
    systemd-cat -t omarchy-shell -- quickshell -n -p "$OMARCHY_PATH/shell" &
  shell_pid=$!

  local status
  while true; do
    wait "$shell_pid"
    status=$?

    # An interrupted wait and a shell killed by that signal report alike.
    kill -0 "$shell_pid" 2>/dev/null || break
  done

  shell_pid=""
  return $status
}

# A compositor busy reconfiguring outputs can miss a query without being gone,
# and that is when the shell dies.
compositor_alive() {
  local attempt

  for attempt in 1 2 3; do
    hyprctl -j monitors >/dev/null 2>&1 && return 0
    (( attempt < 3 )) && sleep 0.5
  done

  return 1
}

# With its crash handler off, a shell that dies of a signal stays dead, and Qt
# leaves through _exit() when the Wayland connection fails, raising no signal at
# all: either way no bar. Supervise those deaths. A clean exit is a deliberate stop
# (omarchy-restart-shell starts its own replacement); a signal here means the
# session is going, and has to reach the shell the launcher used to exec.
terminating=0
shell_pid=""

stop() {
  terminating=1
  [[ -n $shell_pid ]] && kill -TERM "$shell_pid" 2>/dev/null
  return 0
}
trap stop HUP INT TERM

# The startup cover, up until the shell has loaded and reveals the desktop: a
# small instance of its own, with the shell's settings, which fades out when the
# shell says, after 10 seconds at the latest (shell/startup-cover.qml). Only for
# a session's first shell: the shell's intro marks the session as started
# (omarchy-theme-bg-boot-intro), and a restart has no startup to cover. Started
# once: a shell relaunched before that mark reports to it in the same way, and
# one relaunched after it leaves the cover to its 10 seconds.
#
# The first login after first-boot setup covers it with the picture setup left
# on screen in place of the boot logo (omarchy-provision-owner), in the boot
# that ran setup, as only then is it what was on screen. It is taken here
# whether or not a cover starts, so no later login shows or adopts it.
session_marker=$HOME/.local/state/omarchy/background-intro.session-id
setup_cover=$HOME/.local/state/omarchy/setup-cover.png
setup_picture=""
if [[ -f $setup_cover && -d /run/omarchy-provision-owner ]]; then
  mv -f "$setup_cover" "$XDG_RUNTIME_DIR/omarchy-setup-cover.png" && setup_picture=$XDG_RUNTIME_DIR/omarchy-setup-cover.png
fi
rm -f "$setup_cover"

attempts=0
window_started=$SECONDS

while true; do
  # A signal during the backoff only reaches the trap once the sleep is over.
  (( terminating )) && exit 0

  run_shell
  status=$?

  (( terminating )) && exit 0
  (( status == 0 )) && exit 0

  # Relaunching into a session already tearing down burns the attempt budget.
  compositor_alive || exit 0

  if (( SECONDS - window_started > 60 )); then
    attempts=0
    window_started=$SECONDS
  fi

  if (( ++attempts > 5 )); then
    logger -t omarchy-shell "Giving up on the Omarchy shell after $attempts relaunches in under a minute."
    exit 1
  fi

  logger -t omarchy-shell "Omarchy shell exited with status $status; relaunching."
  sleep 1
done
