#!/bin/sh
# axm 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"

archive_url="https://storage.googleapis.com/cl-axiom-production-production-axm/axm/latest/${archive}"
checksums_url="https://storage.googleapis.com/cl-axiom-production-production-axm/axm/latest/checksums.txt"
curl --proto '=https' --tlsv1.2 -fsSL "$archive_url"   -o "$tmp/$archive"
curl --proto '=https' --tlsv1.2 -fsSL "$checksums_url" -o "$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" "$install_dir/axm"; 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 installed to $install_dir/axm (API: axiom.computer)"
