#!/bin/sh

# Run the remote image build with one exit-status contract shared by the Dev
# full and Starter entrypoints. Callers provide ssh_shell and
# classify_remote_exit_137.

# Serialize the one host-wide package mutation shared by otherwise independent
# source builds. A second caller re-checks git after acquiring the lock and
# becomes a no-op once the first installation succeeds.
ensure_remote_git() {
  ssh_shell "
if command -v git >/dev/null 2>&1; then
  exit 0
fi
if ! command -v flock >/dev/null 2>&1; then
  echo 'flock is required to serialize remote package installation' >&2
  exit 1
fi
sudo flock /var/lock/cp9-package-install.lock sh -c 'command -v git >/dev/null 2>&1 || (command -v dnf >/dev/null 2>&1 && dnf install -y git) || (command -v yum >/dev/null 2>&1 && yum install -y git) || (command -v apt-get >/dev/null 2>&1 && apt-get update && apt-get install -y git) || (echo \"git is required for remote Go module fetches\" >&2; exit 1)'
"
}

ensure_remote_cgo() {
  ssh_shell "
if command -v gcc >/dev/null 2>&1 && command -v g++ >/dev/null 2>&1; then
  exit 0
fi
if ! command -v flock >/dev/null 2>&1; then
  echo 'flock is required to serialize remote package installation' >&2
  exit 1
fi
sudo flock /var/lock/cp9-package-install.lock sh -c '((command -v gcc >/dev/null 2>&1 && command -v g++ >/dev/null 2>&1) || (command -v dnf >/dev/null 2>&1 && dnf install -y gcc gcc-c++) || (command -v yum >/dev/null 2>&1 && yum install -y gcc gcc-c++) || (command -v apt-get >/dev/null 2>&1 && apt-get update && apt-get install -y build-essential) || (echo \"gcc and g++ are required for the CGO source build\" >&2; exit 1))'
"
}

run_remote_build() {
  rm -f "$work_dir/image.stamp"
  remote_build_attempt=1
  remote_build_retry_sleep_seconds=${remote_build_retry_sleep_seconds:-2}

  while true; do
    remote_build_started_epoch=$(date +%s)
    if ssh_shell "$remote_cmd"; then
      return 0
    else
      remote_build_status=$?
    fi

    if [ "$remote_build_status" -eq 137 ]; then
      classify_remote_exit_137
    fi
    if [ "$remote_build_status" -ne 255 ] || [ "$remote_build_attempt" -ge 3 ]; then
      return "$remote_build_status"
    fi

    remote_build_attempt=$((remote_build_attempt + 1))
    printf '%s\n' "[cp9 persona build] $service: retry remote docker build/import after SSH transport failure ($remote_build_attempt/3)"
    sleep "$remote_build_retry_sleep_seconds"
  done
}
