#!/bin/sh
# Installs the mo CLI: curl https://cli.momentic.ai/mo | sh
#
# Environment variables:
#   MO_VERSION      version to install (default: latest)
#   MO_INSTALL_DIR  directory to install into (default: $HOME/.local/bin)

set -eu

BUCKET="https://storage.googleapis.com/mo-binaries"
VERSION="${MO_VERSION:-latest}"
INSTALL_DIR="${MO_INSTALL_DIR:-$HOME/.local/bin}"

OS=$(uname -s)
ARCH=$(uname -m)

case "$OS" in
Linux) OS="linux" ;;
Darwin) OS="darwin" ;;
*)
  echo "mo does not support $OS. Supported: Linux, macOS." >&2
  exit 1
  ;;
esac

case "$ARCH" in
x86_64 | amd64) ARCH="x64" ;;
aarch64 | arm64) ARCH="arm64" ;;
*)
  echo "mo does not support $ARCH. Supported: x86_64, arm64." >&2
  exit 1
  ;;
esac

# Alpine and other musl distros cannot run the glibc binary.
LIBC=""
if [ "$OS" = "linux" ]; then
  case "$(ldd /bin/sh 2>&1)" in
  *musl*) LIBC="-musl" ;;
  esac
fi

BINARY="mo-$OS-$ARCH$LIBC"
URL="$BUCKET/$VERSION/$BINARY"

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

echo "Downloading $URL"
if ! curl -fSL --progress-bar "$URL" -o "$TMP/mo"; then
  echo "Failed to download $URL. Check that version $VERSION exists." >&2
  exit 1
fi

# The published checksum guards against a truncated or tampered download.
if curl -fsSL "$URL.sha256" -o "$TMP/mo.sha256"; then
  if command -v sha256sum >/dev/null 2>&1; then
    ACTUAL=$(sha256sum "$TMP/mo" | cut -d' ' -f1)
  elif command -v shasum >/dev/null 2>&1; then
    ACTUAL=$(shasum -a 256 "$TMP/mo" | cut -d' ' -f1)
  else
    ACTUAL=""
    echo "No sha256sum or shasum found, skipping checksum verification." >&2
  fi
  EXPECTED=$(cut -d' ' -f1 "$TMP/mo.sha256")
  if [ -n "$ACTUAL" ] && [ "$ACTUAL" != "$EXPECTED" ]; then
    echo "Checksum mismatch: expected $EXPECTED, got $ACTUAL." >&2
    exit 1
  fi
else
  echo "No checksum published for $BINARY, skipping verification." >&2
fi

mkdir -p "$INSTALL_DIR"
chmod +x "$TMP/mo"
mv -f "$TMP/mo" "$INSTALL_DIR/mo"

echo
echo "Installed mo to $INSTALL_DIR/mo"

# The musl build links against libstdc++, which Alpine does not ship by default.
if [ -n "$LIBC" ] && ! ls /usr/lib/libstdc++.so.* >/dev/null 2>&1; then
  echo
  echo "NOTE: this build needs libstdc++. Install it with 'apk add libstdc++'."
fi

case ":$PATH:" in
*":$INSTALL_DIR:"*)
  echo "Run 'mo --help' to get started."
  ;;
*)
  echo
  echo "NOTE: $INSTALL_DIR is not in your PATH. Add it by running:"
  echo
  echo "  export PATH=\"$INSTALL_DIR:\$PATH\""
  echo
  echo "Add that line to your shell profile (~/.bashrc, ~/.zshrc, etc.) to keep it."
  ;;
esac
