#!/bin/sh
set -eu

COORDINATOR_URL="${HIVE_COORDINATOR_URL:-__COORDINATOR_URL__}"
INSTALL_ROOT="${HOME}/.hive-compute"
VENV_DIR="${INSTALL_ROOT}/venv"
LOG_DIR="${INSTALL_ROOT}/logs"
INSTALL_LOG="${LOG_DIR}/install-$(date +%Y%m%d%H%M%S).log"
HIVE_BIN="${VENV_DIR}/bin/hive"
ENROLLMENT_TOKEN="${HIVE_ENROLLMENT_TOKEN:-}"
ACCEPT_WORKER_AGREEMENT="${HIVE_ACCEPT_WORKER_AGREEMENT:-0}"
PUBLIC_WORKER_ENROLLMENT_ENABLED="__PUBLIC_WORKER_ENROLLMENT_ENABLED__"

mkdir -p "${INSTALL_ROOT}" "${LOG_DIR}"

note() {
  printf '==> %s\n' "$*"
}

fail() {
  printf '\nInstaller failed: %s\n' "$*" >&2
  printf 'Detailed log: %s\n' "${INSTALL_LOG}" >&2
  exit 1
}

refresh_path() {
  export PATH="/opt/homebrew/bin:/opt/homebrew/opt/python@3.12/libexec/bin:/usr/local/bin:/usr/local/opt/python@3.12/libexec/bin:${PATH}"
}

python_meets_requirement() {
  candidate="${1:-}"
  [ -n "${candidate}" ] || return 1
  command -v "${candidate}" >/dev/null 2>&1 || return 1
  "${candidate}" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 12) else 1)' >/dev/null 2>&1
}

run_logged() {
  description="$1"
  shift
  note "${description}"
  if "$@" >>"${INSTALL_LOG}" 2>&1; then
    return 0
  fi
  fail "${description}. See ${INSTALL_LOG}."
}

ensure_homebrew() {
  refresh_path
  if command -v brew >/dev/null 2>&1; then
    return 0
  fi

  note "Homebrew not found. Installing it now."
  NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" >>"${INSTALL_LOG}" 2>&1 \
    || fail "Homebrew installation did not complete successfully"

  if [ -x /opt/homebrew/bin/brew ]; then
    eval "$(/opt/homebrew/bin/brew shellenv)" >>"${INSTALL_LOG}" 2>&1 || true
  elif [ -x /usr/local/bin/brew ]; then
    eval "$(/usr/local/bin/brew shellenv)" >>"${INSTALL_LOG}" 2>&1 || true
  fi

  refresh_path
  command -v brew >/dev/null 2>&1 || fail "Homebrew installed but is still unavailable in PATH"
}

select_python() {
  refresh_path

  if python_meets_requirement python3.12; then
    PYTHON_BIN="$(command -v python3.12)"
    return 0
  fi

  if python_meets_requirement python3; then
    PYTHON_BIN="$(command -v python3)"
    return 0
  fi

  ensure_homebrew
  run_logged "Installing Python 3.12 with Homebrew" brew install python@3.12
  refresh_path

  if python_meets_requirement python3.12; then
    PYTHON_BIN="$(command -v python3.12)"
    return 0
  fi

  fail "Python 3.12 is still unavailable after Homebrew installation"
}

prompt_for_token() {
  if [ -n "${ENROLLMENT_TOKEN}" ]; then
    return 0
  fi

  if [ "${PUBLIC_WORKER_ENROLLMENT_ENABLED}" = "1" ]; then
    note "No enrollment token supplied. Attempting self-serve worker registration."
    return 0
  fi

  [ -r /dev/tty ] || fail "No interactive terminal was found. Re-run with HIVE_ENROLLMENT_TOKEN set."
  printf 'Paste an enrollment token from the HiveCompute manager dashboard: '
  IFS= read -r ENROLLMENT_TOKEN </dev/tty
  [ -n "${ENROLLMENT_TOKEN}" ] || fail "An enrollment token is required to register this Mac"
}

if [ "$(uname -s)" != "Darwin" ]; then
  fail "This installer only supports macOS"
fi

MACOS_MAJOR="$(sw_vers -productVersion | awk -F. '{print $1}')"
if [ "${MACOS_MAJOR}" -lt 13 ]; then
  fail "macOS 13 Ventura or later is required"
fi

select_python
run_logged "Creating the HiveCompute virtual environment" "${PYTHON_BIN}" -m venv "${VENV_DIR}"
run_logged "Upgrading pip tooling" "${VENV_DIR}/bin/python" -m pip install --upgrade pip setuptools wheel
run_logged "Installing HiveCompute worker dependencies" "${VENV_DIR}/bin/pip" install "hive-compute[worker]"

prompt_for_token

note "Registering this Mac with HiveCompute"
set -- "${HIVE_BIN}" onboard --coordinator-url "${COORDINATOR_URL}"
if [ -n "${ENROLLMENT_TOKEN}" ]; then
  set -- "$@" --enrollment-token "${ENROLLMENT_TOKEN}"
fi
if [ "${ACCEPT_WORKER_AGREEMENT}" = "1" ] || [ "${ACCEPT_WORKER_AGREEMENT}" = "true" ] || [ "${ACCEPT_WORKER_AGREEMENT}" = "yes" ]; then
  set -- "$@" --accept-worker-agreement
fi
if ! "$@" >>"${INSTALL_LOG}" 2>&1; then
  fail "Worker onboarding failed"
fi

note "Running worker diagnostics"
if ! "${HIVE_BIN}" doctor >>"${INSTALL_LOG}" 2>&1; then
  fail "Worker diagnostics failed"
fi

cat <<EOF

HiveCompute is installed.

Useful commands:
  ${HIVE_BIN} status
  ${HIVE_BIN} doctor
  ${HIVE_BIN} logs --lines 120

Optional automation:
  HIVE_ACCEPT_WORKER_AGREEMENT=1 curl -fsSL ${COORDINATOR_URL}/install.sh | sh
  HIVE_ENROLLMENT_TOKEN=<token> HIVE_ACCEPT_WORKER_AGREEMENT=1 curl -fsSL ${COORDINATOR_URL}/install.sh | sh

Installer log:
  ${INSTALL_LOG}
EOF
