#!/bin/zsh
set -euo pipefail

API_URL="${ANTBYTES_API_URL:-https://api.antbytes.io}"
DOWNLOAD_URL="${ANTBYTES_DOWNLOAD_URL:-https://antbytes.io/download/agent/releases/AntBytesAgent-v0.4.6-owner-desktop-alerts-macos-universal}"
DEFAULT_ORGANIZATION="${ANTBYTES_ORGANIZATION:-AntBytes Test}"
DEFAULT_SITE="$(scutil --get ComputerName 2>/dev/null || hostname)"
WORK_DIR="$(mktemp -d)"
TTY="/dev/tty"

cleanup() {
  rm -rf "${WORK_DIR}"
}
trap cleanup EXIT

echo "AntBytes Agent macOS Installer"
echo
echo "This will download and install the current AntBytes Agent for this Mac."
echo

if [[ ! -r "${TTY}" ]]; then
  echo "This installer must be run from Terminal."
  exit 1
fi

read "API_KEY?Enrollment/API key: " < "${TTY}"
if [[ -z "${API_KEY}" ]]; then
  echo "Enrollment/API key is required."
  exit 1
fi

read "ORGANIZATION?Organization [${DEFAULT_ORGANIZATION}]: " < "${TTY}"
ORGANIZATION="${ORGANIZATION:-$DEFAULT_ORGANIZATION}"

read "SITE?Site [${DEFAULT_SITE}]: " < "${TTY}"
SITE="${SITE:-$DEFAULT_SITE}"

echo
echo "Downloading AntBytes Agent..."
curl -fL "${DOWNLOAD_URL}" -o "${WORK_DIR}/AntBytesAgent"
chmod +x "${WORK_DIR}/AntBytesAgent"

echo "Installing AntBytes Agent..."
"${WORK_DIR}/AntBytesAgent" install \
  --api-url "${API_URL}" \
  --api-key "${API_KEY}" \
  --organization "${ORGANIZATION}" \
  --site "${SITE}"

echo
echo "Install complete."
echo "Starting AntBytes Agent..."
"${HOME}/Library/Application Support/AntBytes/Agent/bin/AntBytesAgent" run
