#!/bin/sh
# Mbolo installer.
#   curl -fsSL https://mbolo.zaleo.dev/install.sh | sh
# Installs mbolo-node, mbolo-cli and mbolo-sim to ~/.local/bin after checking
# the SHA-256 of the download. Settings (environment):
#   MBOLO_VERSION      version to install (default: the latest release below)
#   MBOLO_INSTALL_DIR  where to put the binaries (default: ~/.local/bin)
set -eu

VERSION="${MBOLO_VERSION:-0.1.0}"
BASE="${MBOLO_BASE_URL:-https://assets.zaleo.dev/mbolo}/$VERSION"
DEST="${MBOLO_INSTALL_DIR:-$HOME/.local/bin}"

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

case "$(uname -s)" in
  Linux) os=linux ;;
  Darwin) os=macos ;;
  *) die "unsupported OS $(uname -s): Linux and macOS only (build from source with cargo otherwise)" ;;
esac
case "$(uname -m)" in
  x86_64 | amd64) arch=x86_64 ;;
  aarch64 | arm64) if [ "$os" = macos ]; then arch=arm64; else arch=aarch64; fi ;;
  *) die "unsupported CPU $(uname -m): x86_64 and arm64 only" ;;
esac
# An x86_64 shell under Rosetta on Apple silicon: take the native build.
if [ "$os" = macos ] && [ "$arch" = x86_64 ] && [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = 1 ]; then
  arch=arm64
fi
name="mbolo-$VERSION-$os-$arch"

if command -v curl >/dev/null 2>&1; then
  fetch() { curl -fsSL --retry 2 -o "$2" "$1"; }
elif command -v wget >/dev/null 2>&1; then
  fetch() { wget -q -O "$2" "$1"; }
else
  die "needs curl or wget"
fi
if command -v sha256sum >/dev/null 2>&1; then
  sha() { sha256sum "$1" | cut -d' ' -f1; }
elif command -v shasum >/dev/null 2>&1; then
  sha() { shasum -a 256 "$1" | cut -d' ' -f1; }
else
  die "needs sha256sum or shasum to check the download"
fi

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

say "Downloading $name.tar.gz"
fetch "$BASE/$name.tar.gz" "$tmp/$name.tar.gz" || die "download failed: $BASE/$name.tar.gz"
fetch "$BASE/SHA256SUMS" "$tmp/SHA256SUMS" || die "download failed: $BASE/SHA256SUMS"

want=$(grep " $name.tar.gz\$" "$tmp/SHA256SUMS" | cut -d' ' -f1)
[ -n "$want" ] || die "no checksum for $name.tar.gz in SHA256SUMS"
got=$(sha "$tmp/$name.tar.gz")
[ "$want" = "$got" ] || die "checksum mismatch for $name.tar.gz (expected $want, got $got)"
say "Checksum OK ($got)"

tar -xzf "$tmp/$name.tar.gz" -C "$tmp"
mkdir -p "$DEST"
for b in mbolo-node mbolo-cli mbolo-sim; do
  cp "$tmp/$name/$b" "$DEST/$b.tmp"
  chmod 755 "$DEST/$b.tmp"
  mv -f "$DEST/$b.tmp" "$DEST/$b"
done
say "Installed mbolo-node, mbolo-cli and mbolo-sim $VERSION to $DEST"

case ":$PATH:" in
  *":$DEST:"*) ;;
  *) say "" ; say "$DEST is not on your PATH. Add it, for example:" ; say "  export PATH=\"$DEST:\$PATH\"" ;;
esac
say ""
say "Next: start a 3-node cluster, see https://mbolo.zaleo.dev/en/docs/"
