#!/bin/sh
# axm-staging installer
set -eu

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

case "$(uname -s)" in
  Linux)  os=linux ;;
  Darwin) os=darwin ;;
  *) echo "axm-install: unsupported OS: $(uname -s)" >&2; exit 1 ;;
esac
case "$(uname -m)" in
  x86_64|amd64)  arch=amd64 ;;
  aarch64|arm64) arch=arm64 ;;
  *) echo "axm-install: unsupported arch: $(uname -m)" >&2; exit 1 ;;
esac

archive="axm_${os}_${arch}.tar.gz"

command -v gcloud >/dev/null || { echo "axm-install: gcloud not found on PATH." >&2; echo "             Install: https://cloud.google.com/sdk/docs/install" >&2; exit 1; }
gcloud auth application-default print-access-token >/dev/null 2>&1 || {
  echo "axm-install: application default credentials not configured." >&2
  echo "             Run: gcloud auth application-default login" >&2
  exit 1
}

gcloud storage cp "gs://silent-matter-483521-r0-staging-axm/axm/latest/${archive}"    "$tmp/$archive"
gcloud storage cp "gs://silent-matter-483521-r0-staging-axm/axm/latest/checksums.txt" "$tmp/checksums.txt"

if command -v sha256sum >/dev/null 2>&1; then
  shatool="sha256sum"
elif command -v shasum >/dev/null 2>&1; then
  shatool="shasum -a 256"
else
  echo "axm-install: neither sha256sum nor shasum found on PATH." >&2
  exit 1
fi
if ! grep " ${archive}\$" "$tmp/checksums.txt" | (cd "$tmp" && $shatool -c -); then
  echo "axm-install: checksum verification failed for $archive." >&2
  exit 1
fi

tar -xzf "$tmp/$archive" -C "$tmp"

install_dir="${INSTALL_DIR:-$HOME/.local/bin}"
mkdir -p "$install_dir"
if ! install -m 0755 "$tmp/axm-staging" "$install_dir/axm-staging"; then
  echo "axm-install: could not write to $install_dir." >&2
  echo "             Set INSTALL_DIR to a writable directory and rerun." >&2
  exit 1
fi

case ":$PATH:" in
  *":$install_dir:"*) ;;
  *) echo "Add $install_dir to your PATH:  export PATH=\"$install_dir:\$PATH\"" ;;
esac

echo "axm-staging installed to $install_dir/axm-staging (API: staging.axiom.computer)"
