#!/usr/bin/env bash

# A script for building macOS binary on a remote macOS host
#
# The helper is expected to be invoked with nomad repo as a first argument, e.g.
# `mac-remote-build ~/go/src/github.com/hashicorp/nomad`.
#
# The repository is required to have a HEAD with all generated files and udpated version committed.
#
# The script runs a host on `sharedmac-bot` host (assumes a corresponding entry in ~/.ssh/config).
# `REMOTE_MACOS_HOST` envvar can be set to point to another macOS host
#
# The script operates by creating a temporary workspace in the remote host to
# contain a clean go installation and gopath with the repository content.
# It should install all dependencies worth pinning, and *not* use system binaries
# that may influence the integrity of the release.
#

set -o errexit

REPO="$1"
RELEASE_TARGET="${2:-release}"

if [[ -z "${REPO}" ]]
then
    echo "repo path is required"
    echo "Usage: $0 <repo_path>"
    exit 1
fi

TMP_WORKSPACE="/tmp/nomad-workspace/$(date +%Y-%m-%d-%s)"
REPO_REMOTE_PATH="${TMP_WORKSPACE}/gopath/src/github.com/hashicorp/nomad"

readonly remote_macos_host=${REMOTE_MACOS_HOST:-sharedmac-bot}

echo "Using temp workspace: ${TMP_WORKSPACE}"
echo

echo '=======>>>> Transfering repository'
ssh ${remote_macos_host} mkdir -p "${REPO_REMOTE_PATH}"
rsync -az \
      "${REPO}/.git" \
      "${remote_macos_host}:${REPO_REMOTE_PATH}"

echo '=======>>>> Compiling Mac Binaries'
cat <<'EOF' | ssh ${remote_macos_host} /bin/bash -s "${TMP_WORKSPACE}" "${RELEASE_TARGET}"

set -o errexit
set -o xtrace

TMP_WORKSPACE="$1"
RELEASE_TARGET="$2"
REPO_PATH="${TMP_WORKSPACE}/gopath/src/github.com/hashicorp/nomad"


mkdir -p "${TMP_WORKSPACE}/tmp"

install_go() {
  local go_version="1.24.2"
  local download=

  download="https://storage.googleapis.com/golang/go${go_version}.darwin-amd64.tar.gz"
  curl -sSL --fail -o "${TMP_WORKSPACE}/tmp/go.tar.gz" ${download}

  tar -C "${TMP_WORKSPACE}" -xf "${TMP_WORKSPACE}/tmp/go.tar.gz"
}

install_release_deps() {
  go get -u github.com/a8m/tree/cmd/tree
}

compile() {
  cd "${REPO_PATH}"
  git checkout .
  git status
  git log -1
  make ${RELEASE_TARGET}
}

install_go

export GOPATH="${TMP_WORKSPACE}/gopath"
export PATH="${TMP_WORKSPACE}/go/bin:${GOPATH}/bin:$PATH"

install_release_deps
compile

EOF

echo '=======>>>> Retrieving mac compiled binaries'
rsync -avz --ignore-existing ${remote_macos_host}:"${REPO_REMOTE_PATH}/pkg/" "${REPO}/pkg"

ssh ${remote_macos_host} chmod -R +w "${TMP_WORKSPACE}" || true
ssh ${remote_macos_host} rm -rf "${TMP_WORKSPACE}" || true
