#!/usr/bin/env sh
# Generated deployment assets serve this installer at /download/install.sh.

set -eu

BASE_URL="https://cli.fencio.dev/download"
CLI_VERSION="0.5.8"
platform="$(uname -s | tr '[:upper:]' '[:lower:]')"
architecture="$(uname -m)"

case "$platform/$architecture" in
  darwin/arm64) artifact="fencio-cli-${CLI_VERSION}-darwin-arm64.tgz" ;;
  linux/x86_64) artifact="fencio-cli-${CLI_VERSION}-linux-x64.tgz" ;;
  *)
    printf 'Fencio has no package for %s/%s.\n' "$platform" "$architecture" >&2
    exit 1
    ;;
esac

command -v curl >/dev/null 2>&1 || {
  printf 'Fencio setup needs curl. Install curl and rerun.\n' >&2
  exit 1
}

# Hold the read-only checker in memory; do not create client files first.
prerequisites="$(curl -fsSL "$BASE_URL/prerequisites.sh")" || {
  printf 'Cannot download prerequisite checks. Nothing was installed.\n' >&2
  exit 1
}
printf '%s\n' "$prerequisites" | sh -s -- "$@" --base-only
# fencio setup skips its own copy of the base check when it sees this.
export FENCIO_BASE_CHECKED=1

install_root="${FENCIO_INSTALL_ROOT:-$HOME/.local/share/fencio-cli}"
bin_dir="${FENCIO_BIN_DIR:-$HOME/.local/bin}"
mkdir -p "$install_root" "$bin_dir"

cache_bust="$(date +%s)"
printf 'Downloading Fencio %s for %s/%s…\n' \
  "$CLI_VERSION" "$platform" "$architecture"
if ! npm install --no-fund --no-audit --loglevel error \
  --prefix "$install_root" \
  "$BASE_URL/$artifact?cachebust=$cache_bust"; then
  printf 'Fencio package installation failed: %s/%s\n' \
    "$BASE_URL" "$artifact" >&2
  exit 1
fi
ln -sf "$install_root/node_modules/.bin/fencio" "$bin_dir/fencio"

# Record which build this is, so fencio --update knows when a newer one
# exists. Best effort: without it the first update simply reinstalls.
stamp_dir="${XDG_CONFIG_HOME:-$HOME/.config}/fencio/control-plane"
mkdir -p "$stamp_dir"
if command -v curl >/dev/null 2>&1; then
  curl -fsS "$BASE_URL/$artifact.sha256" > "$stamp_dir/client.sha256.tmp" \
    2>/dev/null && mv "$stamp_dir/client.sha256.tmp" \
    "$stamp_dir/client.sha256" || rm -f "$stamp_dir/client.sha256.tmp"
fi
export PATH="$bin_dir:$PATH"

printf 'Installed Fencio at %s\n' "$bin_dir/fencio"
# CLI-only bootstrap leaves runtime and application changes to setup.
if [ "${1:-}" = "--cli-only" ]; then
  [ "$#" -eq 1 ] || {
    printf 'Use --cli-only without integration options.\n' >&2
    exit 2
  }
  exit 0
fi
# Repair updates the CLI package and Python runtime only, without setup.
if [ "${1:-}" = "--repair-ghost" ]; then
  [ "$#" -eq 1 ] || {
    printf 'Use --repair-ghost without integration options.\n' >&2
    exit 2
  }
  exec "$bin_dir/fencio" repair ghost
fi
# Installer selection flags enter the same public connection command.
if [ "${1:-}" = "--integrations" ]; then
  shift
  integration_names="${1:?integration names are required}"
  shift
  exec "$bin_dir/fencio" integrations connect "$integration_names" "$@"
fi
exec "$bin_dir/fencio" setup "$@"
