#!/usr/bin/env bash
set -euo pipefail

# OpenMeerkat Native Linux Hub Installer
# Source: https://github.com/fortytwo-oclock/meerkat42
REPO_URL="${MEERKAT_REPO_URL:-https://github.com/fortytwo-oclock/meerkat42.git}"
INSTALL_DIR="${MEERKAT_SRC_DIR:-/opt/openmeerkat-src}"

echo "==> OpenMeerkat Native Linux Hub Installer (Public Beta)"
if [ "$(id -u)" -ne 0 ]; then
  echo "Please run as root (e.g. curl -fsSL https://meerkatnode.com | sudo bash)" >&2
  exit 1
fi

command -v git >/dev/null 2>&1 || { echo "git is required. Install git and re-run." >&2; exit 1; }

if [ -d "$INSTALL_DIR/.git" ]; then
  echo "==> Updating existing checkout in $INSTALL_DIR"
  git -C "$INSTALL_DIR" pull --ff-only
else
  echo "==> Cloning $REPO_URL -> $INSTALL_DIR"
  git clone --depth 1 "$REPO_URL" "$INSTALL_DIR"
fi

if [ ! -f "$INSTALL_DIR/scripts/install-hub.sh" ]; then
  echo "Installer script scripts/install-hub.sh not found on default branch yet." >&2
  echo "Inspect releases at: https://github.com/fortytwo-oclock/meerkat42/releases" >&2
  exit 1
fi

exec bash "$INSTALL_DIR/scripts/install-hub.sh" "$@"
