#!/bin/sh
# MainLayer endpoint agent installer.
#   curl -fsSL https://mainlayer.ai/install.sh | sh
#   curl -fsSL https://mainlayer.ai/install.sh | sh -s -- --token enr_...        # install + enroll + start (recommended)
#   curl -fsSL https://mainlayer.ai/install.sh | sh -s -- --version v0.1.0 --bin-dir ~/.local/bin
# Downloads the release for this OS/CPU from mainlayer.ai, verifies its SHA-256 checksum and installs `mainlayer`.
# With --token it also enrolls this machine with your organization (the token is single-use and expires in
# 15 minutes) and installs the background service and AI tool hooks. Without --token nothing is configured.
set -eu

BASE_URL="${MAINLAYER_BASE_URL:-https://mainlayer.ai/downloads}"
VERSION=""
BIN_DIR=""
TOKEN="${MAINLAYER_ENROLL_TOKEN:-}"
SERVER="${MAINLAYER_SERVER:-https://api.mainlayer.ai}"
LABEL=""
NO_SERVICE=""

while [ $# -gt 0 ]; do
  case "$1" in
    --version) VERSION="$2"; shift 2 ;;
    --bin-dir) BIN_DIR="$2"; shift 2 ;;
    --token) TOKEN="$2"; shift 2 ;;
    --server) SERVER="$2"; shift 2 ;;
    --label) LABEL="$2"; shift 2 ;;
    --no-service) NO_SERVICE=1; shift ;;
    -h|--help) sed -n '2,6p' "$0" 2>/dev/null || true; exit 0 ;;
    *) echo "unknown option: $1" >&2; exit 2 ;;
  esac
done

say() { printf '\033[1;34m==>\033[0m %s\n' "$*"; }
die() { printf '\033[1;31merror:\033[0m %s\n' "$*" >&2; exit 1; }

command -v curl >/dev/null 2>&1 || die "curl is required"
command -v tar  >/dev/null 2>&1 || die "tar is required"

OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)
case "$OS" in
  darwin|linux) ;;
  *) die "unsupported OS: $OS (Windows: download the .zip from $BASE_URL)" ;;
esac
case "$ARCH" in
  x86_64|amd64) ARCH=amd64 ;;
  arm64|aarch64) ARCH=arm64 ;;
  *) die "unsupported CPU architecture: $ARCH" ;;
esac

if [ -z "$VERSION" ]; then
  VERSION=$(curl -fsSL "$BASE_URL/latest.txt" | tr -d '[:space:]') || die "could not resolve the latest version"
fi

NAME="mainlayer_${VERSION}_${OS}_${ARCH}"
URL="$BASE_URL/$VERSION/$NAME.tar.gz"
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

say "Downloading mainlayer $VERSION for $OS/$ARCH"
curl -fsSL "$URL" -o "$TMP/$NAME.tar.gz" || die "download failed: $URL"
curl -fsSL "$BASE_URL/$VERSION/checksums.txt" -o "$TMP/checksums.txt" || die "checksum file missing"

EXPECTED=$(grep " $NAME.tar.gz\$" "$TMP/checksums.txt" | awk '{print $1}')
[ -n "$EXPECTED" ] || die "no checksum listed for $NAME.tar.gz"
if command -v shasum >/dev/null 2>&1; then ACTUAL=$(shasum -a 256 "$TMP/$NAME.tar.gz" | awk '{print $1}');
else ACTUAL=$(sha256sum "$TMP/$NAME.tar.gz" | awk '{print $1}'); fi
[ "$EXPECTED" = "$ACTUAL" ] || die "checksum mismatch for $NAME.tar.gz"
say "Checksum verified"

tar -C "$TMP" -xzf "$TMP/$NAME.tar.gz"
chmod +x "$TMP/mainlayer"

if [ -z "$BIN_DIR" ]; then
  if [ -w /usr/local/bin ]; then BIN_DIR=/usr/local/bin; else BIN_DIR="$HOME/.local/bin"; fi
fi
mkdir -p "$BIN_DIR"
mv "$TMP/mainlayer" "$BIN_DIR/mainlayer"
say "Installed $BIN_DIR/mainlayer"

case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *) printf '\nAdd it to your PATH, e.g.:\n  export PATH="%s:$PATH"\n' "$BIN_DIR" ;;
esac

if [ -n "$TOKEN" ]; then
  say "Enrolling this machine with $SERVER"
  if [ -n "$LABEL" ]; then "$BIN_DIR/mainlayer" enroll --server "$SERVER" --token "$TOKEN" --label "$LABEL"
  else "$BIN_DIR/mainlayer" enroll --server "$SERVER" --token "$TOKEN"; fi || die "enrollment failed (the token may be expired or already used; ask your admin for a new one)"
  if [ -z "$NO_SERVICE" ]; then
    say "Installing the background service and AI tool hooks"
    "$BIN_DIR/mainlayer" install || die "service installation failed; run '$BIN_DIR/mainlayer install' manually"
    say "Done. Check with: $BIN_DIR/mainlayer status"
  else
    say "Enrolled. Start the service later with: $BIN_DIR/mainlayer install"
  fi
  printf '
MainLayer never collects keystrokes, screen captures or terminal history. Details: https://mainlayer.ai/privacy
'
  exit 0
fi

cat <<MSG

Next steps:
  1. Ask your MainLayer admin for an enrollment command, or generate one in the portal (People & Seats).
  2. mainlayer enroll --server $SERVER --token enr_...
  3. mainlayer install     # background service + AI tool hooks (backs up every file it touches)
  4. mainlayer status

MainLayer never collects keystrokes, screen captures or terminal history. Details: https://mainlayer.ai/privacy
MSG
