# pacman runs pre_remove only on a real removal (an upgrade calls pre_upgrade),
# so this reports the uninstall the same way the .deb/.rpm remove script does.
# Close the copies still running from this package (every person's), as uninstall.sh
# does: apt, dnf, zypper and pacman never stop programs, so the tray icon stayed until
# logout (VM tests 2026-11-17, Manjaro and openSUSE). Only /usr/bin/voxtyper, so an
# AppImage copy is left alone; /proc and coreutils only (no pkill on minimal systems).
_voxtyper_stop() {
  pids=
  for p in /proc/[0-9]*; do
    exe=$(readlink "$p/exe" 2>/dev/null)
    if [ -z "$exe" ]; then
      # Link hidden (some containers): its name and how it was started instead.
      [ "$(cat "$p/comm" 2>/dev/null)" = voxtyper ] || continue
      exe=$(tr '\0' '\n' < "$p/cmdline" 2>/dev/null | head -n 1)
      [ "$exe" = voxtyper ] && exe=/usr/bin/voxtyper
    fi
    [ "$exe" = /usr/bin/voxtyper ] && pids="$pids ${p#/proc/}"
  done
  [ -n "$pids" ] || return 0
  kill $pids 2>/dev/null || :
  for _ in 1 2 3 4 5 6 7 8 9 10; do
    alive=
    for pid in $pids; do kill -0 "$pid" 2>/dev/null && alive="$alive $pid"; done
    [ -n "$alive" ] || return 0
    sleep 0.3
  done
  kill -9 $alive 2>/dev/null || :
}
pre_remove() {
  for cfg in /home/*/.config/voxtyper-desktop/settings.json /root/.config/voxtyper-desktop/settings.json; do
    [ -f "$cfg" ] || continue
    home=${cfg%/.config/voxtyper-desktop/settings.json}
    user=$(stat -c %U "$cfg" 2>/dev/null) || continue
  # Their session bus, when they are logged in, so the app can also remove its
  # GNOME custom shortcut.
  uid=$(stat -c %u "$cfg" 2>/dev/null) || continue
  bus=
  [ -S "/run/user/$uid/bus" ] && bus="DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$uid/bus XDG_RUNTIME_DIR=/run/user/$uid"
    if command -v runuser >/dev/null 2>&1; then
      timeout 15 runuser -u "$user" -- env HOME="$home" $bus /usr/bin/voxtyper --report-uninstall >/dev/null 2>&1 || true
    else
      group=$(stat -c %G "$cfg" 2>/dev/null) || continue
      timeout 15 chroot --userspec="$user:$group" / env HOME="$home" $bus /usr/bin/voxtyper --report-uninstall >/dev/null 2>&1 || true
    fi
  done
  _voxtyper_stop
  return 0
}

# The udev rule for the virtual keyboard (same steps as the .deb/.rpm postinst).
_voxtyper_uinput() {
  modprobe uinput >/dev/null 2>&1 || :
  udevadm control --reload-rules >/dev/null 2>&1 || :
  udevadm trigger --action=change --subsystem-match=misc --sysname-match=uinput >/dev/null 2>&1 || :
  udevadm settle --timeout=5 >/dev/null 2>&1 || :
}
post_install() { _voxtyper_uinput; }
post_upgrade() { _voxtyper_uinput; }
