#!/bin/sh
# cmeta installer — downloads the right prebuilt binary for your OS/arch from
# the site (no GitHub round-trip), verifies its SHA-256, and installs it.
#
#   curl -fsSL https://ipok.dev/install.sh | bash
#
# Override the source with CMETA_BASE, the install dir with CMETA_BIN_DIR.
set -eu

BASE="${CMETA_BASE:-https://ipok.dev}"
DL="$BASE/dl"

say()  { printf '%s\n' "$*"; }
err()  { printf 'cmeta-install: %s\n' "$*" >&2; exit 1; }

# --- detect platform ---------------------------------------------------------
os=$(uname -s 2>/dev/null || echo unknown)
arch=$(uname -m 2>/dev/null || echo unknown)
case "$os" in
  Linux)  OS=linux ;;
  Darwin) OS=darwin ;;
  *) err "unsupported OS: $os (try the manual downloads on the datasets page)" ;;
esac
case "$arch" in
  x86_64|amd64)  ARCH=amd64 ;;
  arm64|aarch64) ARCH=arm64 ;;
  *) err "unsupported architecture: $arch" ;;
esac

ARCHIVE="cmeta_${OS}_${ARCH}.tar.gz"
say "→ platform: ${OS}/${ARCH}"

# --- tooling -----------------------------------------------------------------
if command -v curl >/dev/null 2>&1; then
  fetch() { curl -fsSL "$1" -o "$2"; }
elif command -v wget >/dev/null 2>&1; then
  fetch() { wget -qO "$2" "$1"; }
else
  err "need curl or wget"
fi
if command -v sha256sum >/dev/null 2>&1; then
  sha() { sha256sum "$1" | awk '{print $1}'; }
elif command -v shasum >/dev/null 2>&1; then
  sha() { shasum -a 256 "$1" | awk '{print $1}'; }
else
  sha() { echo ""; }  # no tool: skip verification (warn below)
fi

tmp=$(mktemp -d 2>/dev/null || mktemp -d -t cmeta)
trap 'rm -rf "$tmp"' EXIT

# --- download + verify -------------------------------------------------------
say "→ downloading $ARCHIVE"
fetch "$DL/$ARCHIVE" "$tmp/$ARCHIVE" || err "download failed (no release published yet?)"

if fetch "$DL/checksums.txt" "$tmp/checksums.txt" 2>/dev/null; then
  want=$(grep " $ARCHIVE\$" "$tmp/checksums.txt" 2>/dev/null | awk '{print $1}' | head -n1)
  got=$(sha "$tmp/$ARCHIVE")
  if [ -n "$want" ] && [ -n "$got" ]; then
    [ "$want" = "$got" ] || err "checksum mismatch (expected $want, got $got)"
    say "→ checksum ok"
  else
    say "→ checksum skipped (no tool or entry)"
  fi
fi

# --- extract + install -------------------------------------------------------
tar -xzf "$tmp/$ARCHIVE" -C "$tmp" || err "extract failed"
[ -f "$tmp/cmeta" ] || err "archive did not contain the cmeta binary"
chmod +x "$tmp/cmeta"

if [ -n "${CMETA_BIN_DIR:-}" ]; then
  BIN="$CMETA_BIN_DIR"
elif [ -w /usr/local/bin ] 2>/dev/null; then
  BIN=/usr/local/bin
else
  BIN="$HOME/.local/bin"
fi
mkdir -p "$BIN"
mv "$tmp/cmeta" "$BIN/cmeta" || err "could not install to $BIN"

say "✓ installed cmeta to $BIN/cmeta"
case ":$PATH:" in
  *":$BIN:"*) : ;;
  *) say "  note: $BIN is not on your PATH — add it, e.g.:"
     say "    export PATH=\"$BIN:\$PATH\"" ;;
esac
say ""
say "try:  cmeta me"
