#!/bin/sh
# Metric Ingest CLI agent installer — https://metric-ingest.com/docs#cli
# Usage: curl -fsSL https://metric-ingest.com/install.sh | sh
set -eu

OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)
case "$ARCH" in
  x86_64|amd64) ARCH=amd64 ;;
  aarch64|arm64) ARCH=arm64 ;;
  *) echo "mi: unsupported architecture: $ARCH" >&2; exit 1 ;;
esac
case "$OS" in
  linux|darwin) : ;;
  *) echo "mi: unsupported OS: $OS" >&2; exit 1 ;;
esac

VERSION="${MI_VERSION:-latest}"
DEST="${MI_INSTALL_DIR:-/usr/local/bin}"
BASE="https://metric-ingest.com/dl"
NAME="mi_${VERSION}_${OS}_${ARCH}"

echo "Installing mi (${VERSION}) for ${OS}/${ARCH} into ${DEST}..."
tmp=$(mktemp)
curl -fsSL "${BASE}/${NAME}" -o "$tmp"

# Verify the checksum if sha256sum/shasum is available.
if sums=$(curl -fsSL "${BASE}/checksums.txt" 2>/dev/null); then
  want=$(printf '%s\n' "$sums" | awk -v n="$NAME" '$2==n{print $1}')
  if [ -n "$want" ]; then
    if command -v sha256sum >/dev/null 2>&1; then got=$(sha256sum "$tmp" | awk '{print $1}')
    elif command -v shasum >/dev/null 2>&1; then got=$(shasum -a 256 "$tmp" | awk '{print $1}')
    else got=""; fi
    if [ -n "$got" ] && [ "$got" != "$want" ]; then
      echo "mi: checksum mismatch, aborting" >&2; rm -f "$tmp"; exit 1
    fi
  fi
fi

chmod +x "$tmp"
if [ -w "$DEST" ]; then mv "$tmp" "$DEST/mi"; else sudo mv "$tmp" "$DEST/mi"; fi

echo "Done. Next:"
echo "  mi run --key \$MI_WRITE_KEY --scrape http://localhost:9090/metrics --interval 15s"
