#!/usr/bin/env bash

#
# install-dependencies-osx-jenkins
#
# Copyright (C) 2022 by RStudio, PBC
#
# Unless you have received this program directly from RStudio pursuant
# to the terms of a commercial license agreement with RStudio, then
# this program is licensed to you under the terms of version 3 of the
# GNU Affero General Public License. This program is distributed WITHOUT
# ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
# AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
#
#

set -e
source "$(dirname "${BASH_SOURCE[0]}")/../tools/rstudio-tools.sh"

# if we're called with no arguments, then re-invoke the script
# with the architecture(s) we're installing Homebrew for
if [ "$#" = "0" ]; then

   if [ "$(arch)" = "arm64" ]; then
      # recursively invoke self with different architecture on arm64
      arch -arm64  "${BASH_SOURCE[0]}" "arm64"
      arch -x86_64 "${BASH_SOURCE[0]}" "x86_64"
   else
      # assume x86_64 otherwise and run as normal
      "${BASH_SOURCE[0]}" "x86_64"
   fi

   exit 0

fi

require-program git

ARCH="$1"
info "Installing Homebrew for ${ARCH}"

HOMEBREW_PREFIX="${HOME}/homebrew/${ARCH}"
if [ -d "${HOMEBREW_PREFIX}" ]; then
   echo "Homebrew for ${ARCH} already installed at ${HOMEBREW_PREFIX}"
   exit 0
fi

mkdir -p "${HOMEBREW_PREFIX}"
cd "${HOMEBREW_PREFIX}"

git init
git remote add origin https://github.com/homebrew/brew
git fetch origin
git checkout master

