#!/bin/bash

# omarchy:summary=Watch for process crashes and OOM kills and notify the user
# omarchy:hidden=true

# systemd-coredump journals every core dump under COREDUMP_MESSAGE_ID with
# structured COREDUMP_* fields. systemd journals systemd-oomd kills under
# OOMD_KILL_MESSAGE_ID and kernel cgroup OOM kills under OOM_KILL_MESSAGE_ID
# with USER_UNIT.

set -uo pipefail

# See systemd.journal-fields(7) and systemd/sd-messages.h.
readonly COREDUMP_MESSAGE_ID=fc2e22bc6ee647b6b90729ab34a250b1
readonly OOMD_KILL_MESSAGE_ID=d989611b15e44c9dbf31e3c81256e4ed
readonly OOM_KILL_MESSAGE_ID=fe6faa94e7774663a0da52717891d8ef

# nf-md-robot_dead and nf-md-memory, escaped so this file reads without a Nerd Font.
readonly CRASH_GLYPH=$'\U000f16a1'
readonly OOM_GLYPH=$'\U000f035b'

# Crash loops dump core repeatedly, so announce each program at most once a
# window.
readonly dedupe_seconds=${OMARCHY_CRASH_DEDUPE_SECONDS:-60}

# Suppress secondary crash toasts briefly after an OOM kill: when systemd-oomd
# kills an app's scope, sibling or parent processes (such as Chrome's browser
# process) often trap and dump core right afterward.
readonly oom_grace_seconds=${OMARCHY_OOM_CRASH_GRACE_SECONDS:-15}

# Extended regex of process names never worth announcing.
readonly ignore_pattern=${OMARCHY_CRASH_IGNORE:-}

declare -A last_notified
declare -A last_oom_notified
last_oom_at=0

# Resolve a systemd USER_UNIT (such as
# app-Hyprland-google\x2dchrome\x2dstable-5ab4d154.scope) to a user-facing app
# name via its .desktop entry, falling back to the unescaped identifier.
oom_app_name() {
  local unit=$1 id dir candidate name terminal_id
  local -a dirs=()

  [[ $unit == app-*.scope || $unit == app-*.service ]] || return 0
  unit=${unit%.scope}
  unit=${unit%.service}
  unit=$(systemd-escape --unescape -- "$unit" 2>/dev/null) || return 0

  # Strip trailing UWSM/systemd random hex or PID scope suffix.
  if [[ $unit == */* && ${unit##*/} =~ ^([0-9a-fA-F]{8}|[0-9]+)$ ]]; then
    unit=${unit%/*}
  fi

  id=${unit##*/}
  id=${id%%@*}
  [[ -n $id ]] || return 0

  # Fallback terminal launches run through xdg-terminal-exec, so UWSM names
  # the scope after the wrapper rather than the terminal itself.
  if [[ $id == "xdg-terminal-exec" ]]; then
    terminal_id=$(xdg-terminal-exec --print-id 2>/dev/null || true)
    terminal_id=${terminal_id%%:*}
    [[ -n $terminal_id ]] && id=${terminal_id%.desktop}
  fi

  IFS=':' read -ra dirs <<<"${XDG_DATA_HOME:-$HOME/.local/share}:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"
  for dir in "${dirs[@]}"; do
    [[ -d $dir/applications ]] || continue
    # Strip -stable so binaries like google-chrome-stable match google-chrome.desktop.
    for candidate in "$id" "${id%-stable}" "${id,,}"; do
      [[ -f $dir/applications/$candidate.desktop ]] || continue
      name=$(awk -F= '{ sub(/\r$/, "") }
        /^\[/ { in_entry = ($0 == "[Desktop Entry]") }
        in_entry && $1 == "Name" { sub(/^[^=]*=/, ""); print; exit }' \
        "$dir/applications/$candidate.desktop")
      if [[ -n $name ]]; then
        printf '%s' "$name"
        return 0
      fi
    done
  done

  [[ $id == *.*.* ]] && id=${id##*.}
  printf '%s' "$id"
}

recent_oom() {
  local t=$1
  (( last_oom_at && t >= last_oom_at - 1 && t - last_oom_at <= oom_grace_seconds ))
}

announce_crash() {
  local comm=$1 pid=$2 exe=$3 signal=$4

  # The shell owns org.freedesktop.Notifications, so a shell crash takes the
  # notification server down with it and a toast sent into that gap is lost.
  # Wait for the restarted shell to claim the name again: the crash least
  # likely to be delivered is the one most worth reporting.
  omarchy-notification-wait || return 1

  # --exec rather than a libnotify action: the shell runs clicks from its own
  # hint and never emits ActionInvoked. Keeps the default "omarchy-action" app
  # name, the only one shouldBypassDnd() lets through. Crash details ride as
  # discrete argv words, so a hostile process name can't be reparsed as a
  # command. --exec consumes the rest of the line, so it comes last.
  omarchy-notification-send \
    --urgency critical \
    --glyph "$CRASH_GLYPH" \
    "$(omarchy-i18n crash.processCrashed "$comm")" \
    "$(omarchy-i18n crash.diagnose)" \
    --exec omarchy-agent-crash "$pid" "$comm" "$exe" "$signal"
}

# With OOMPolicy=continue (used on terminal scopes), a kernel cgroup OOM kill
# only stops the offending child process while the app unit stays active.
oom_unit_survived() {
  local unit=$1 prop policy="" state=""

  [[ $unit != "-" ]] || return 1
  while IFS= read -r prop; do
    case "$prop" in
      OOMPolicy=*) policy=${prop#OOMPolicy=} ;;
      ActiveState=*) state=${prop#ActiveState=} ;;
    esac
  done < <(systemctl --user show --property=OOMPolicy --property=ActiveState -- "$unit" 2>/dev/null)

  [[ $policy == "continue" && $state == "active" ]]
}

announce_oom() {
  local app_name=$1 survived=${2:-0} body

  omarchy-notification-wait || return 1

  if (( survived )); then
    if [[ -n $app_name ]]; then
      body=$(omarchy-i18n oom.stoppedProcess "$app_name")
    else
      body=$(omarchy-i18n oom.stoppedProcessGeneric)
    fi
  elif [[ -n $app_name ]]; then
    body=$(omarchy-i18n oom.closed "$app_name")
  else
    body=$(omarchy-i18n oom.closedGeneric)
  fi

  omarchy-notification-send \
    --urgency critical \
    --glyph "$OOM_GLYPH" \
    "$(omarchy-i18n oom.title)" \
    "$body"
}

# -n 0 so a restart does not re-announce events already dealt with. Passing
# multiple MESSAGE_ID= matches tells journalctl to OR them into one stream.
journalctl -f -n 0 -o json \
  "MESSAGE_ID=$COREDUMP_MESSAGE_ID" \
  "MESSAGE_ID=$OOMD_KILL_MESSAGE_ID" \
  "MESSAGE_ID=$OOM_KILL_MESSAGE_ID" 2>/dev/null |
  while IFS= read -r entry; do
    # A dash for a field that is empty, missing, or non-string (journalctl
    # emits non-UTF-8 values as byte arrays): tab is IFS whitespace, so an
    # empty field collapses into the next delimiter and shifts fields along.
    IFS=$'\t' read -r msg_id uid comm pid exe signal user_unit rt_us cd_us < <(
      jq -r 'def field:
               if type == "string" and . != "" then
                 gsub("[\t\r\n]"; "") | if . == "" then "-" else . end
               else "-"
               end;
             [(.MESSAGE_ID | field),
              (._UID | field),
              (.COREDUMP_COMM | field),
              (.COREDUMP_PID | field),
              (.COREDUMP_EXE | field),
              (.COREDUMP_SIGNAL_NAME | field),
              (.USER_UNIT | field),
              (.__REALTIME_TIMESTAMP | field),
              (.COREDUMP_TIMESTAMP | field)] | join("\t")' <<<"$entry" 2>/dev/null
    )

    # Only this user's events; a daemon dying is a sysadmin's problem.
    [[ $uid =~ ^[0-9]+$ ]] || continue
    ((uid == UID)) || continue

    if [[ $msg_id == $OOMD_KILL_MESSAGE_ID || $msg_id == $OOM_KILL_MESSAGE_ID ]]; then
      # Kernel OOM events can propagate to parent slices; notify only for the
      # killed unit itself.
      [[ $user_unit == *.slice ]] && continue

      now=$EPOCHSECONDS
      last_oom_at=$now
      [[ $rt_us =~ ^[0-9]{7,}$ ]] && last_oom_at=$(( rt_us / 1000000 ))

      oom_app=""
      [[ $user_unit != "-" ]] && oom_app=$(oom_app_name "$user_unit")
      oom_survived=0
      if [[ $msg_id == $OOM_KILL_MESSAGE_ID ]] && oom_unit_survived "$user_unit"; then
        oom_survived=1
      fi
      oom_key="${oom_app:-generic}:$oom_survived"

      (((now - ${last_oom_notified[$oom_key]:-0}) < dedupe_seconds)) && continue
      announce_oom "$oom_app" "$oom_survived" && last_oom_notified[$oom_key]=$now
      continue
    fi

    [[ $pid =~ ^[0-9]+$ ]] || continue

    # The toast only offers a diagnosis, so it has nothing to offer until an
    # agent is chosen. Checked per crash, not at startup, so picking one takes
    # effect without restarting this service.
    [[ -n $(omarchy-default-agent) ]] || continue

    now=$EPOCHSECONDS
    crash_at=$now
    [[ $cd_us =~ ^[0-9]{7,}$ ]] && crash_at=$(( cd_us / 1000000 ))
    recent_oom "$crash_at" && continue

    # comm is truncated to 15 characters, so prefer the executable's basename.
    name=$comm
    [[ $exe == /* ]] && name=${exe##*/}

    # A process can set its own comm to anything prctl takes, slashes included,
    # and a crash with no recorded executable falls back to it. The mute below
    # turns this name into a path, so keep it one component: a crash must not
    # reach a flag outside crash-ignore/, nor have a diagnosis write one there.
    name=${name##*/}

    # What that leaves is not always a name. "/" leaves nothing, which is no
    # kind of array subscript and no kind of toast; a dot component names a
    # directory rather than a flag, so a mute on it would touch that directory
    # and then never match; and a dash is what the read above puts there when
    # the crash recorded no name at all.
    [[ -n $name && $name != "-" && $name != "." && $name != ".." ]] || name=unknown

    [[ -n $ignore_pattern && $name =~ $ignore_pattern ]] && continue

    # Never announce our own machinery, or it notifies about itself.
    [[ $name == omarchy-crash-* || $name == omarchy-agent-* ]] && continue

    # Muted at the end of a diagnosis, when the user was offered it and said
    # yes. A flag per program rather than one list, so omarchy-crash-mute can
    # lift one without reading, rewriting and re-parsing the rest.
    omarchy-toggle-enabled "crash-ignore/$name" && continue

    (((now - ${last_notified[$name]:-0}) < dedupe_seconds)) && continue

    # Only a delivered toast starts the dedupe window. A failed send that
    # counted would suppress the rest of a crash loop for a minute, and
    # `journalctl -n 0` never replays what was missed.
    announce_crash "$name" "$pid" "$exe" "$signal" && last_notified[$name]=$now
  done
