#!/bin/bash
# The aarch64 package runs its pacman hooks and its mkinitcpio wrapper through
# this, so that only an Apple Silicon Mac behaves differently from upstream:
#
#   limine-apple-gate COMMAND...            COMMAND, except on a Mac that has not activated Limine
#   limine-apple-gate --mac COMMAND...      COMMAND on a Mac only
#   limine-apple-gate --not-mac COMMAND...  COMMAND everywhere but a Mac
#   limine-apple-gate --mac                 succeeds on a Mac only
#
# A Mac boots GRUB until Omarchy activates Limine: the gate
# /var/lib/omarchy/limine.enabled and the /etc/default/limine the activation
# writes, the same test as omarchy-mac-limine-active. A command that does not
# run reads the targets pacman streams to it and succeeds quietly.

gate=/var/lib/omarchy/limine.enabled
limine_default=/etc/default/limine
compatible=(/proc/device-tree/compatible /sys/firmware/devicetree/base/compatible)

# Fixtures fake the machine for an unprivileged caller only; as root, which
# pacman hooks always are, the live system decides.
if ((EUID != 0)); then
  gate=${OMARCHY_LIMINE_GATE:-$gate}
  limine_default=${OMARCHY_LIMINE_DEFAULT:-$limine_default}
  if [[ -n ${OMARCHY_PROC_ROOT:-}${OMARCHY_SYS_ROOT:-} ]]; then
    compatible=()
    [[ -z ${OMARCHY_PROC_ROOT:-} ]] || compatible+=("$OMARCHY_PROC_ROOT/device-tree/compatible")
    [[ -z ${OMARCHY_SYS_ROOT:-} ]] || compatible+=("$OMARCHY_SYS_ROOT/firmware/devicetree/base/compatible")
  fi
fi

# m1n1 names every Apple Silicon Mac "apple,<model>" in the root node's
# NUL-separated compatible list, as omarchy-hw-platform reads it.
is_mac() {
  local source
  for source in "${compatible[@]}"; do
    [[ -r $source ]] && tr '\0' '\n' <"$source" | grep -q '^apple,' && return 0
  done
  return 1
}

# pacman writes NeedsTargets to a socket and fails the write if the hook has
# gone; hooks without NeedsTargets get no stdin at all.
pass() {
  if [[ -S /dev/stdin || -p /dev/stdin ]]; then
    cat >/dev/null
  fi
  exit 0
}

mode=limine
case ${1:-} in
--mac | --not-mac)
  mode=${1#--}
  shift
  ;;
esac

if (($# == 0)); then
  [[ $mode == mac ]] && { is_mac; exit; }
  echo "usage: limine-apple-gate [--mac|--not-mac] COMMAND [ARG]..." >&2
  exit 2
fi

case $mode in
mac) is_mac || pass ;;
not-mac) ! is_mac || pass ;;
limine) ! is_mac || [[ -e $gate && -f $limine_default ]] || pass ;;
esac
exec "$@"
