#!/bin/sh
# Sintropyc installer.
#   curl -fsSL https://install.sintropyc.com/install.sh | sh
# Then:
#   sintropyc system start
#
# Override the host for testing:
#   curl -fsSL http://<server-ip>/install.sh | SINTROPYC_BASE_URL=http://<server-ip> sh
set -eu

BASE_URL="${SINTROPYC_BASE_URL:-https://install.sintropyc.com}"

OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"
case "$ARCH" in
  x86_64 | amd64) ARCH=amd64 ;;
  aarch64 | arm64) ARCH=arm64 ;;
  *) echo "sintropyc: unsupported architecture: $ARCH" >&2; exit 1 ;;
esac
if [ "$OS" != "linux" ]; then
  echo "sintropyc: only Linux is supported (got $OS)" >&2
  exit 1
fi

BIN="sintropyc-$OS-$ARCH"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

echo "Downloading $BIN ..."
curl -fsSL "$BASE_URL/bin/$BIN" -o "$TMP/sintropyc"

# Verify integrity when a checksum file and sha256sum are available.
if curl -fsSL "$BASE_URL/bin/SHA256SUMS" -o "$TMP/SHA256SUMS" 2>/dev/null \
   && command -v sha256sum >/dev/null 2>&1; then
  expected="$(grep "  $BIN\$" "$TMP/SHA256SUMS" | awk '{print $1}')"
  actual="$(sha256sum "$TMP/sintropyc" | awk '{print $1}')"
  if [ -n "$expected" ] && [ "$expected" != "$actual" ]; then
    echo "sintropyc: checksum mismatch, aborting" >&2
    exit 1
  fi
  [ -n "$expected" ] && echo "checksum verified."
fi

chmod +x "$TMP/sintropyc"
DEST=/usr/local/bin/sintropyc
if [ "$(id -u)" = 0 ] || [ -w /usr/local/bin ]; then
  mv "$TMP/sintropyc" "$DEST"
else
  echo "Installing to $DEST (requires sudo)..."
  sudo mv "$TMP/sintropyc" "$DEST"
fi
trap - EXIT
rm -rf "$TMP"

echo ""
echo "  installed: $DEST"
echo "  next step:"
echo ""
echo "      sintropyc system start"
echo ""
