#!/usr/bin/env bash
# Installs the Pratimāna Matrix command line, `matrix`, for the current user.
#
#   curl -fsSL https://matrix.pratimana.com/install.sh | bash
#
# One Python file, standard library only, placed in ~/.local/bin (or
# $MATRIX_INSTALL_DIR) and verified against the checksum the site
# publishes next to it. Nothing runs as root and nothing else is touched.
# Uninstall: rm ~/.local/bin/matrix ~/.config/matrix -r
set -euo pipefail

SITE="${MATRIX_SITE:-https://matrix.pratimana.com}"
DIR="${MATRIX_INSTALL_DIR:-$HOME/.local/bin}"
NAME="matrix"

say() { printf '%s\n' "$*"; }
fail() { printf 'install.sh: %s\n' "$*" >&2; exit 1; }

# Python 3.8 or newer, wherever it is called python3 or python.
PY=""
for candidate in python3 python; do
  if command -v "$candidate" >/dev/null 2>&1; then
    if "$candidate" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 8) else 1)' 2>/dev/null; then
      PY="$(command -v "$candidate")"
      break
    fi
  fi
done
[ -n "$PY" ] || fail "Python 3.8 or newer is needed. Install it (macOS: xcode-select --install, Debian/Ubuntu: apt install python3) and run this again."

command -v curl >/dev/null 2>&1 || fail "curl is needed."

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

say "Downloading $SITE/cli/matrix.py"
curl -fsSL "$SITE/cli/matrix.py" -o "$TMP/matrix.py" || fail "could not download $SITE/cli/matrix.py"

# The checksum the site publishes beside the file. When it is there, it
# has to match; when the site does not offer one, the download stands.
if curl -fsSL "$SITE/cli/matrix.sha256" -o "$TMP/matrix.sha256" 2>/dev/null; then
  EXPECTED="$(awk '{print $1}' "$TMP/matrix.sha256")"
  if command -v sha256sum >/dev/null 2>&1; then
    ACTUAL="$(sha256sum "$TMP/matrix.py" | awk '{print $1}')"
  elif command -v shasum >/dev/null 2>&1; then
    ACTUAL="$(shasum -a 256 "$TMP/matrix.py" | awk '{print $1}')"
  else
    ACTUAL="$("$PY" -c 'import hashlib,sys; print(hashlib.sha256(open(sys.argv[1],"rb").read()).hexdigest())' "$TMP/matrix.py")"
  fi
  [ "$EXPECTED" = "$ACTUAL" ] || fail "the download does not match the published checksum; nothing installed."
  say "Checksum verified"
fi

head -c 200 "$TMP/matrix.py" | grep -q "Pratimāna Matrix from the terminal" || fail "the download does not look like the matrix command; nothing installed."

mkdir -p "$DIR"
# Pin the interpreter that passed the version check, so the command runs
# with it even on a machine where `python3` is not first on PATH.
{ printf '#!%s\n' "$PY"; tail -n +2 "$TMP/matrix.py"; } > "$TMP/$NAME"
chmod 755 "$TMP/$NAME"
mv -f "$TMP/$NAME" "$DIR/$NAME"

say "Installed $DIR/$NAME ($("$DIR/$NAME" version))"

case ":$PATH:" in
  *":$DIR:"*) ;;
  *)
    say ""
    say "$DIR is not on your PATH yet. Add it to your shell profile:"
    say "  export PATH=\"$DIR:\$PATH\""
    ;;
esac

say ""
say "Next: $NAME login"
say "Docs: $SITE/docs"
