#!/usr/bin/env bash
set -euo pipefail

HOST=${HOST:-}
PHASE=${PHASE:-about}
MACMINI_DEBUG=${MACMINI_DEBUG:-0}

# Require HOST to be specified
if [ -z "$HOST" ]; then
  echo "❌ ERROR: HOST environment variable is required"
  echo ""
  echo "Usage:"
  echo "  HOST=agent01 yarn macmini:install"
  echo "  HOST=agent02 yarn macmini:about"
  echo "  HOST=agent03 yarn macmini:clean"
  echo ""
  exit 1
fi

# Collect all arguments intended for remote phase (after PHASE)
ARGS=("$@")

# Build a simple space‑separated list (flags expected; minimal quoting needed)
REMOTE_ARGS="${ARGS[*]:-}" # empty if none

# Optional debug echo
if [ "${MACMINI_DEBUG}" = "1" ]; then
  echo "[local] HOST=$HOST PHASE=$PHASE REMOTE_ARGS=$REMOTE_ARGS"
fi

# Stage required files on remote
# Upload setup script and version files to /tmp (temporary execution files)
scp scripts/setup-mac-mini.sh .ci-versions .node-version .ruby-version .java-version .xcode-version "jenkinsagent@$HOST:/tmp/"
# Upload mise.toml to home directory (persists, mise auto-discovers it)
scp mise.toml "jenkinsagent@$HOST:~/"

# Compose remote command
# For 'init' phase: use non-login shell since .bashrc doesn't exist yet and init creates it
# For other phases: use login shell to source .bashrc and activate mise
if [ "$PHASE" = "init" ]; then
  SHELL_FLAG=""  # non-login shell
else
  SHELL_FLAG="-l"  # login shell
fi

REMOTE_CMD="MACMINI_DEBUG=$MACMINI_DEBUG CI_VERSIONS_FILE=/tmp/.ci-versions bash $SHELL_FLAG /tmp/setup-mac-mini.sh $PHASE $REMOTE_ARGS"

ssh -tt "jenkinsagent@$HOST" "$REMOTE_CMD"
