#!/bin/bash -pu

bootstrap-homebrew() {
  local brew_file git_executable repository target

  brew_file="$0"
  while [[ -L "${brew_file}" ]]
  do
    target="$(readlink "${brew_file}")" || exit 1
    if [[ "${target}" != /* ]]
    then
      target="$(cd -P "${brew_file%/*}" && pwd)/${target}" || exit 1
    fi
    brew_file="${target}"
  done

  repository="$(cd -P "${brew_file%/*}/.." && pwd)" || exit 1
  git_executable="$(command -v git)"
  if [[ -z "${git_executable}" ]] || ! "${git_executable}" --version &>/dev/null
  then
    echo "Error: Git is required to update Homebrew." >&2
    exit 1
  fi

  cd "${repository}" || exit 1
  if ! "${git_executable}" -c core.hooksPath=/dev/null fetch --force --quiet origin \
       refs/heads/main:refs/remotes/origin/main
  then
    echo "Error: Failed to fetch Homebrew's main branch." >&2
    exit 1
  fi
  if ! "${git_executable}" -c core.hooksPath=/dev/null checkout --quiet -B main origin/main
  then
    echo "Error: Failed to switch Homebrew to its main branch." >&2
    exit 1
  fi
  "${git_executable}" remote set-head origin main || exit 1

  [[ "${1:-}" == "update-report" ]] && exit 0
  exec "${repository}/bin/brew" "$@"
}

if [[ "${1:-}" != "update" && "${1:-}" != "update-report" ]]
then
  echo "Error: Homebrew's master branch is no longer supported." >&2
  echo "Run \`brew update\` to migrate to the main branch." >&2
  exit 1
fi

echo "Warning: Support for migrating Homebrew from master to main will be" >&2
echo "removed on 1 March 2027." >&2
bootstrap-homebrew "$@"
