#!/usr/bin/env bash
#===============================================================================
#
#             FILE: brew.sh
#            USAGE: bash brew.sh
#
#      DESCRIPTION: installs the Homebrew package manager on a fresh macOS and
#                   wires 'brew shellenv' into ~/.zprofile. Idempotent: if brew
#                   is already installed it just ensures the shellenv line.
#
#     REQUIREMENTS: macOS, curl, bash
#
#       OS SUPPORT: macOS (Apple Silicon or Intel)
#
#           AUTHOR: Guto Carvalho, guto@bolha.io
#             SITE: https://gutocarvalho.net
#         MASTODON: @gutocarvalho@bolha.us
#         PIXELFED: @gutocarvalho@bolha.photos
#      WRITEFREELY: @gutocarvalho@bolha.blog
#       MATTERMOST: @gutocarvalho:mattermost.bolha.chat
#
#     ORGANIZATION: gutocarvalho.net, gcn.sh, bolha.io
#
#          CREATED: 2026-08-13
#          UPDATED: 2026-08-13
#             REPO: https://gitlab.gutocarvalho.net/open/install
#
#     CONTRIBUTORS: name, email, mastodon
#
#     The code is simple on purpose: we want it to be friendly for people
#     that are starting with shell language and programming logic.
#
#     Do NOT run this as root. Homebrew installs the Xcode Command Line Tools
#     for you if they are missing (you may be asked for your password by sudo).
#
#===============================================================================

set -o nounset                              # treat unset variables as an error

## 1. CONSTANTS/VARIABLES ######################################################

BREW_INSTALLER="https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh"
ZPROFILE="$HOME/.zprofile"

## 2. HELPERS #################################################################

### abort: print an error message and stop the script
function abort() {
  echo -e "\nError: $1" >&2
  echo -e "Tip: run 'bash -x brew.sh' to see exactly what failed.\n" >&2
  exit 1
}

### check_macos: this script only runs on macOS
function check_macos() {
  if [ "$(uname -s)" != "Darwin" ]; then
    abort "this script only runs on macOS."
  fi
}

### check_not_root: Homebrew (and this script) must NOT run as root
function check_not_root() {
  if [ "$(id -u)" = "0" ]; then
    abort "do NOT run this as root. Run it as your normal user."
  fi
}

### need_cmd: make sure a required command exists
function need_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    abort "'$1' is required but was not found. Please install it first."
  fi
}

### brew_bin: print the path to the brew binary for this machine (empty if none)
function brew_bin() {
  if [ -x /opt/homebrew/bin/brew ]; then
    echo /opt/homebrew/bin/brew      # Apple Silicon
  elif [ -x /usr/local/bin/brew ]; then
    echo /usr/local/bin/brew         # Intel
  fi
}

### wire_shellenv: add 'brew shellenv' to ~/.zprofile (once) and load it now
function wire_shellenv() {
  local brew="$1"
  if ! grep -qF "$brew shellenv" "$ZPROFILE" 2>/dev/null; then
    echo "eval \"\$($brew shellenv)\"" >> "$ZPROFILE"
    echo "added 'brew shellenv' to $ZPROFILE"
  fi
  eval "$("$brew" shellenv)"
}

## 3. INSTALL FUNCTIONS #######################################################

### 3.1 install homebrew (non-interactive)
function install_brew() {
  echo -e "\n>>> Installing Homebrew...\n"
  NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL "$BREW_INSTALLER")" \
    || abort "the Homebrew installer failed."
}

## 4. EXECUTING ###############################################################

check_macos
check_not_root
need_cmd curl

if command -v brew >/dev/null 2>&1; then
  echo -e "\nHomebrew is already installed: $(brew --version | head -n1)"
  wire_shellenv "$(command -v brew)"
else
  install_brew
  BREW="$(brew_bin)"
  [ -n "$BREW" ] || abort "Homebrew was installed but the brew binary was not found."
  wire_shellenv "$BREW"
fi

## 5. NOTIFICATIONS ###########################################################

echo -e "\n----------------------------------------------------------------------------------"
echo -e "\nAll done! Homebrew is ready: $(brew --version | head -n1)"
echo "It is now available at $(command -v brew)."
echo -e "\nOpen a new terminal (or run 'source ~/.zprofile') so 'brew' is on your PATH."
echo -e "\nEnjoy it!"
echo -e "\nWant to know more about our collective? Visit https://bolha.io and consider joining us! ;)"
echo -e "Come and visit our mastodon instance:    https://bolha.us"
echo -e "Come and visit our mattermost instance:  https://mattermost.bolha.chat"
echo -e "Say hello on the fediverse:              @gutocarvalho@bolha.us"
echo -e "\n----------------------------------------------------------------------------------\n"
