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

# Stamped per release. Keep DEFAULT_PACKAGE_SHA256 in sync with the tgz
# served at DEFAULT_PACKAGE_URL (see checksums.txt next to this script).
DEFAULT_PACKAGE_URL="https://agentar.antdigital.com/agentar-cli/package.tgz"
DEFAULT_PACKAGE_SHA256="368f74c81f5c64ea511c54fddebb9e2bdd173ec0da45b704af9d34fedaca4140"

PACKAGE_URL="${AGENTAR_CLI_PACKAGE_URL:-${DEFAULT_PACKAGE_URL}}"
PACKAGE_SHA256="${AGENTAR_CLI_PACKAGE_SHA256:-}"
NPM_PREFIX="${AGENTAR_CLI_PREFIX:-}"
SKIP_CHECKSUM="${AGENTAR_CLI_SKIP_CHECKSUM:-0}"
CUSTOM_PACKAGE_URL=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --prefix)
      if [[ $# -lt 2 ]]; then
        echo "Error: --prefix requires a directory." >&2
        exit 1
      fi
      NPM_PREFIX="$2"
      shift 2
      ;;
    --prefix=*)
      NPM_PREFIX="${1#--prefix=}"
      shift
      ;;
    --global)
      NPM_PREFIX=""
      shift
      ;;
    --package-url)
      if [[ $# -lt 2 ]]; then
        echo "Error: --package-url requires a URL." >&2
        exit 1
      fi
      PACKAGE_URL="$2"
      CUSTOM_PACKAGE_URL=1
      shift 2
      ;;
    --package-url=*)
      PACKAGE_URL="${1#--package-url=}"
      CUSTOM_PACKAGE_URL=1
      shift
      ;;
    --sha256)
      if [[ $# -lt 2 ]]; then
        echo "Error: --sha256 requires a hex digest." >&2
        exit 1
      fi
      PACKAGE_SHA256="$2"
      shift 2
      ;;
    --sha256=*)
      PACKAGE_SHA256="${1#--sha256=}"
      shift
      ;;
    --skip-checksum)
      SKIP_CHECKSUM=1
      shift
      ;;
    -h|--help)
      cat <<'USAGE'
Usage: install.sh [--global] [--prefix <dir>] [--package-url <url>] [--sha256 <hex>] [--skip-checksum]

Downloads the Agentar CLI package, verifies its SHA-256 checksum, then
installs it with npm from the verified local file.

Options:
  --global             Install into the npm global prefix. This is the default.
  --prefix <dir>       Install into a custom npm prefix instead of the npm global prefix.
  --package-url <url>  Override the package URL (e.g. a newer uploaded tarball).
                       Checksum verification is skipped unless --sha256 is given.
  --sha256 <hex>       Expected SHA-256 of the downloaded package.
  --skip-checksum      Skip checksum verification (not recommended).

Environment variables:
  AGENTAR_CLI_PACKAGE_URL     Mirror URL for the same release package.
                              The built-in checksum is still verified.
  AGENTAR_CLI_PACKAGE_SHA256  Same as --sha256.
  AGENTAR_CLI_PREFIX          Same as --prefix.
  AGENTAR_CLI_SKIP_CHECKSUM=1 Same as --skip-checksum.

Published checksums: see checksums.txt under the same download path.
USAGE
      exit 0
      ;;
    *)
      echo "Error: unknown argument: $1" >&2
      exit 1
      ;;
  esac
done

if ! command -v npm >/dev/null 2>&1; then
  echo "Error: npm is required to install agentar-cli." >&2
  exit 1
fi
if ! command -v curl >/dev/null 2>&1; then
  echo "Error: curl is required to download agentar-cli." >&2
  exit 1
fi

# Resolve the expected checksum: explicit value wins; the built-in value only
# applies to the release package (default URL or a mirror of it).
if [[ -z "${PACKAGE_SHA256}" && "${CUSTOM_PACKAGE_URL}" -eq 0 ]]; then
  PACKAGE_SHA256="${DEFAULT_PACKAGE_SHA256}"
fi

sha256_of() {
  if command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | awk '{print $1}'
  elif command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | awk '{print $1}'
  else
    echo ""
  fi
}

WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/agentar-cli-install.XXXXXX")"
trap 'rm -rf "${WORK_DIR}"' EXIT
PACKAGE_FILE="${WORK_DIR}/agentar-cli.tgz"

echo "Downloading agentar-cli package from ${PACKAGE_URL}"
curl -fsSL "${PACKAGE_URL}" -o "${PACKAGE_FILE}"

if [[ "${SKIP_CHECKSUM}" == "1" ]]; then
  echo "Warn: checksum verification skipped by request." >&2
elif [[ -z "${PACKAGE_SHA256}" ]]; then
  echo "Warn: no expected SHA-256 for custom --package-url; pass --sha256 to verify." >&2
else
  ACTUAL_SHA256="$(sha256_of "${PACKAGE_FILE}")"
  if [[ -z "${ACTUAL_SHA256}" ]]; then
    echo "Error: neither shasum nor sha256sum is available to verify the package." >&2
    echo "Re-run with --skip-checksum only if you accept an unverified install." >&2
    exit 1
  fi
  if [[ "${ACTUAL_SHA256}" != "${PACKAGE_SHA256}" ]]; then
    echo "Error: package checksum mismatch, refusing to install." >&2
    echo "  expected: ${PACKAGE_SHA256}" >&2
    echo "  actual:   ${ACTUAL_SHA256}" >&2
    exit 1
  fi
  echo "Package checksum verified (sha256: ${ACTUAL_SHA256})"
fi

NPM_ARGS=(install -g "${PACKAGE_FILE}")
if [[ -n "${NPM_PREFIX}" ]]; then
  mkdir -p "${NPM_PREFIX}"
  NPM_ARGS+=(--prefix "${NPM_PREFIX}")
fi

echo "Installing agentar-cli from verified local package"
npm "${NPM_ARGS[@]}"

if [[ -n "${NPM_PREFIX}" ]]; then
  AGENTAR_BIN="${NPM_PREFIX}/bin/agentar"
else
  AGENTAR_BIN="$(command -v agentar || true)"
  if [[ -z "${AGENTAR_BIN}" ]]; then
    GLOBAL_PREFIX="$(npm prefix -g)"
    AGENTAR_BIN="${GLOBAL_PREFIX}/bin/agentar"
  fi
fi

if [[ -z "${AGENTAR_BIN}" || ! -x "${AGENTAR_BIN}" ]]; then
  echo "Warn: agentar executable was not found after install." >&2
  if [[ -z "${NPM_PREFIX}" ]]; then
    echo "If npm installed successfully, ensure your npm global bin directory is on PATH." >&2
  else
    echo "Add to PATH for this shell: export PATH=\"${NPM_PREFIX}/bin:\$PATH\"" >&2
  fi
  exit 0
fi

"${AGENTAR_BIN}" --version >/dev/null 2>&1 || "${AGENTAR_BIN}" --help >/dev/null
echo "agentar-cli installed successfully: ${AGENTAR_BIN}"
if [[ -n "${NPM_PREFIX}" ]]; then
  echo "Add to PATH for this shell: export PATH=\"${NPM_PREFIX}/bin:\$PATH\""
else
  echo "Run agentar with: agentar --help"
fi
