#!/bin/bash

# omarchy:summary=Check or signal the current user's recording processes
# omarchy:args=[--pid <pid>] [--signal INT|KILL]
# omarchy:hidden=true

usage() {
  echo "Usage: omarchy-capture-screenrecording-process [--pid <pid>]... [--signal INT|KILL]" >&2
  exit 2
}

proc_root=${OMARCHY_PROC_ROOT:-/proc}
wanted_pids=()
declare -A wanted_seen=()
signal=""

while (($#)); do
  case $1 in
    --pid)
      # Compare textually first: bash arithmetic wraps values past 64 bits.
      [[ ${2-} =~ ^0*([0-9]+)$ ]] || usage
      pid=${BASH_REMATCH[1]}
      ((${#pid} <= 10 && 10#$pid <= 4194304)) || usage
      pid=$((10#$pid))
      if [[ -z ${wanted_seen[$pid]:-} ]]; then
        wanted_seen[$pid]=1
        wanted_pids+=("$pid")
      fi
      shift 2
      ;;
    --signal)
      [[ ${2-} == "INT" || ${2-} == "KILL" ]] || usage
      signal=$2
      shift 2
      ;;
    *)
      usage
      ;;
  esac
done

is_recorder() {
  local exe
  exe=$(readlink "$proc_root/$1/exe" 2>/dev/null) || return 1
  # Linux appends this when an upgrade unlinks a still-running executable.
  exe=${exe% (deleted)}
  exe=${exe##*/}
  [[ $exe == "gpu-screen-recorder" || $exe == "wf-recorder" ]]
}

comm_is_recorder() {
  local comm
  { IFS= read -r comm <"$proc_root/$1/comm"; } 2>/dev/null || return 1
  [[ $comm == "gpu-screen-reco" || $comm == "gpu-screen-recorder" || $comm == "wf-recorder" ]]
}

# Linux truncates a process name to 15 characters: gpu-screen-recorder runs as
# gpu-screen-reco, which any executable sharing that prefix also matches, and a
# process can rename itself, so the executable path confirms each candidate.
# Reading $proc_root/*/comm directly avoids pgrep's full /proc stat/status walk.
matched=()
if ((${#wanted_pids[@]} > 0)); then
  for pid in "${wanted_pids[@]}"; do
    if [[ -O $proc_root/$pid ]] && comm_is_recorder "$pid" && is_recorder "$pid"; then
      matched+=("$pid")
    fi
  done
else
  shopt -s nullglob
  comm_files=("$proc_root"/[0-9]*/comm)
  if ((${#comm_files[@]} > 0)); then
    while IFS= read -r file; do
      pid=${file#"$proc_root"/}
      pid=${pid%/comm}
      if [[ -O $proc_root/$pid ]] && is_recorder "$pid"; then
        matched+=("$pid")
      fi
    done < <(grep -lE '^(gpu-screen-reco(rder)?|wf-recorder)$' "${comm_files[@]}" 2>/dev/null)
  fi
fi

if ((${#matched[@]} == 0)); then
  exit 1
fi

if [[ -n $signal ]]; then
  delivered=0
  for pid in "${matched[@]}"; do
    # The pid can be reused between discovery and kill; re-checking exe here narrows that window.
    if is_recorder "$pid" && kill "-$signal" "$pid" 2>/dev/null; then
      delivered=1
    fi
  done
  # A recorder that exits before its signal has stopped anyway; fail only if none was signalled.
  ((delivered)) || exit 1
fi

exit 0
