#!/bin/sh
# ElephantPool — mahout installer (Linux x86_64)
#
# Usage:  curl -fsSL https://elephantpool.ai/install-mahout.sh | sh
#
# This script is the canonical source for https://elephantpool.ai/install-mahout.sh —
# the release job publishes it next to the binary it installs. It downloads the
# prebuilt binary, verifies its SHA-256 against the published checksum, and only
# then puts it on your PATH. Nothing is started; nothing runs as root.
#
# Environment:
#   MAHOUT_DEST   install directory (default: $HOME/.local/bin)
#   MAHOUT_BASE   base URL to download from (default: https://elephantpool.ai)
set -e

BASE="${MAHOUT_BASE:-https://elephantpool.ai}"
DEST="${MAHOUT_DEST:-$HOME/.local/bin}"

OS=$(uname -s)
ARCH=$(uname -m)
if [ "$OS" != "Linux" ] || [ "$ARCH" != "x86_64" ]; then
  echo "mahout installer: only Linux x86_64 prebuilts exist for now (got $OS/$ARCH)."
  echo "Windows and macOS are on the roadmap. Build from source meanwhile:"
  echo "  https://gitlab.debuck.info/elephantpool-oss/mahout"
  exit 1
fi

for cmd in curl sha256sum; do
  command -v "$cmd" >/dev/null 2>&1 || { echo "mahout installer: '$cmd' is required."; exit 1; }
done

mkdir -p "$DEST"
TMP=$(mktemp "${TMPDIR:-/tmp}/mahout.XXXXXX")
trap 'rm -f "$TMP"' EXIT INT TERM

echo "Downloading mahout…"
curl -fsSL "$BASE/dl/mahout-linux-x86_64" -o "$TMP"

# The checksum file is standard sha256sum output ("<hash>  <filename>"); take the
# hash field so the check works whether or not the filename column is present.
EXPECTED=$(curl -fsSL "$BASE/dl/mahout-linux-x86_64.sha256" | awk 'NR==1 {print $1}')
ACTUAL=$(sha256sum "$TMP" | awk '{print $1}')
if [ -z "$EXPECTED" ] || [ "$EXPECTED" != "$ACTUAL" ]; then
  echo "sha256 mismatch — aborting."
  echo "  expected: ${EXPECTED:-<none published>}"
  echo "  actual:   $ACTUAL"
  exit 1
fi

chmod 755 "$TMP"
mv "$TMP" "$DEST/mahout"
trap - EXIT INT TERM

echo "mahout installed to $DEST/mahout ($("$DEST/mahout" version 2>/dev/null | head -1 || echo 'installed'))"
case ":$PATH:" in
  *":$DEST:"*) ;;
  *) echo "NOTE: $DEST is not on your PATH — add it, or run $DEST/mahout directly." ;;
esac
echo "Next: get a link code from https://app.elephantpool.ai (Machines), then run:"
echo "  mahout up --code <CODE> --endpoint https://app.elephantpool.ai/api/hosts"
