#!/bin/bash
#
# postinstall — runs as root after the .pkg installs Brew.app
#
# Installs Homebrew for the current console user if it is not already present.
# Because pkg scripts run as root, we delegate to the logged-in user so that
# Homebrew ends up owned by them (in /opt/homebrew on Apple Silicon, or
# /usr/local on Intel), not by root.

set -euo pipefail

# ---------------------------------------------------------------------------
# Identify the console user. On a normal interactive install this will be the
# person sitting at the machine; it will be empty on headless/MDM installs.
# ---------------------------------------------------------------------------
CURRENT_USER=$(stat -f "%Su" /dev/console 2>/dev/null || true)

if [[ -z "$CURRENT_USER" || "$CURRENT_USER" == "root" ]]; then
    echo "postinstall: could not determine console user — skipping Homebrew installation." >&2
    exit 0
fi

# ---------------------------------------------------------------------------
# Check whether Homebrew is already installed for this user.
# We check the two canonical prefix locations rather than relying on PATH,
# which may not be set correctly when running under the installer daemon.
# ---------------------------------------------------------------------------
HOMEBREW_PREFIX_ARM="/opt/homebrew"
HOMEBREW_PREFIX_INTEL="/usr/local"

if [[ -x "$HOMEBREW_PREFIX_ARM/bin/brew" || -x "$HOMEBREW_PREFIX_INTEL/bin/brew" ]]; then
    echo "postinstall: Homebrew already installed — skipping." >&2
    exit 0
fi

# ---------------------------------------------------------------------------
# Install Homebrew as the console user.
#
# TODO: Consider whether you want to run this non-interactively. The official
# install script supports NONINTERACTIVE=1 to skip prompts and accept all
# defaults, which is usually appropriate for a bundled installer. Remove the
# variable if you want the script to prompt the user normally.
# ---------------------------------------------------------------------------
echo "postinstall: installing Homebrew for user '$CURRENT_USER'…" >&2

su - "$CURRENT_USER" -c \
    'NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"'

echo "postinstall: Homebrew installation complete." >&2
exit 0
