#!/bin/bash

# omarchy:summary=Ask the browser kept running hidden to quit before its service stops
# omarchy:hidden=true

# Run as ExecStop of omarchy-browser-prewarm.service with its $MAINPID. At
# startup the browser moves itself into an app-*.scope of its own, so stopping
# the service kills the zygote and GPU helpers it left behind but never signals
# the browser, which then aborts with a core dump. Asked first, while its
# helpers are still alive, it shuts down cleanly. ExecStop runs inside the
# service's cgroup, so the browser is the process that has left it.
main=${MAINPID:-}
[[ -n $main ]] || exit 0
cgroup_root=${OMARCHY_CGROUP_ROOT:-/sys/fs/cgroup}
# Only the unified hierarchy's line counts: a cgroup v1 hierarchy some service
# mounts (a VPN's net_cls, say) adds a line of its own.
unit_cgroup=$(sed -n 's/^0:://p' "${OMARCHY_SELF_CGROUP:-/proc/$$/cgroup}")
unit_procs="$cgroup_root$unit_cgroup/cgroup.procs"
# Unable to tell who left the unit, signal nobody and leave it to systemd.
[[ -n $unit_cgroup && -r $unit_procs ]] || exit 0

left_unit() {
  [[ -e /proc/$1 ]] && ! grep -qx "$1" "$unit_procs"
}

browsers=()
if left_unit "$main"; then
  # Started straight into the browser, as Arch's chromium script does with
  # exec. Its own children, like an extension's native messaging host, quit
  # with it.
  browsers=("$main")
else
  # A vendor wrapper, like the one brave-origin ships, runs the browser as its
  # child and doesn't pass signals on.
  for pid in $(pgrep -P "$main"); do
    if left_unit "$pid"; then
      browsers+=("$pid")
    fi
  done
fi
(( ${#browsers[@]} )) || exit 0

kill -TERM "${browsers[@]}" 2>/dev/null

# Within the user manager's 2s DefaultTimeoutStopSec, after which systemd
# kills it anyway.
for _ in {1..15}; do
  kill -0 "${browsers[@]}" 2>/dev/null || exit 0
  sleep 0.1
done
