#!/bin/bash
#
# Purpose : Stop a full system upgrade (pacman -Syu, yay -Syu, ...) that isn't
#           run by CoreDesktop's update or install. pacman runs this as root
#           before each transaction (system/pacman-guard.sh installs the hook);
#           exiting non-zero aborts it.
#
# update skips its snapshot, keyring, mirror and initramfs checks, migrations
# and AUR rebuilds when pacman upgrades the system on its own. update and
# install.sh export COREDESKTOP_ALLOW_PACMAN=1, and so can you to get past this:
#   COREDESKTOP_ALLOW_PACMAN=1 sudo pacman -Syu

# For the tests: where to read processes from, and which process is pacman
PROC="${PACMAN_GUARD_PROC:-/proc}"
pacman_pid="${PACMAN_GUARD_PID:-$PPID}"

# pacman's arguments, one per line. pacman runs its hooks itself, so it's the
# parent.
args=()
[ -r "$PROC/$pacman_pid/cmdline" ] && mapfile -d '' -t args < "$PROC/$pacman_pid/cmdline"

sync=0 sysupgrade=0
for arg in "${args[@]:1}"; do
  case "$arg" in
    --) break ;;
    --sync) sync=1 ;;
    --sysupgrade) sysupgrade=1 ;;
    --*) ;;
    -*)
      [[ "$arg" == *S* ]] && sync=1
      [[ "$arg" == *u* ]] && sysupgrade=1 ;;
  esac
done
(( sync && sysupgrade )) || exit 0

# Allowed when pacman or any process that started it has the variable: sudo
# drops it from pacman's environment, but the sudo process itself still has it
pid="$pacman_pid"
while [[ "$pid" =~ ^[0-9]+$ ]] && (( pid > 1 )); do
  if tr '\0' '\n' < "$PROC/$pid/environ" 2> /dev/null | grep -qx 'COREDESKTOP_ALLOW_PACMAN=1'; then
    exit 0
  fi
  pid="$(awk '/^PPid:/ { print $2 }' "$PROC/$pid/status" 2> /dev/null)"
done

cat >&2 << 'EOF'

This is a full system upgrade outside CoreDesktop's update, so pacman stopped
before changing anything. Run this instead:

  update

update also takes a snapshot first, updates the keyring and mirrors, checks the
new initramfs, runs CoreDesktop's migrations and updates the AUR packages.

To upgrade with pacman alone anyway:

  COREDESKTOP_ALLOW_PACMAN=1 sudo pacman -Syu

EOF
exit 1
