#!/usr/bin/env bash
# setup-caveman.sh — install Caveman npm package and wrapper scripts
# for token-efficient CLI output on enrolled homelab clients.
set -euo pipefail

CLONE_DIR="${HOMELAB_CONTEXT_DIR:-/opt/homelab}"
BIN_DIR="$HOME/bin"
TOOLS_DIR="$CLONE_DIR/tools"

mkdir -p "$BIN_DIR"

# Install the caveman npm package globally.
if ! command -v caveman >/dev/null 2>&1; then
    if command -v npm >/dev/null 2>&1; then
        npm install -g caveman 2>/dev/null || true
        echo "[setup-caveman] caveman npm package installed"
    fi
fi

# Copy wrapper to ~/bin.
if [ -f "$TOOLS_DIR/caveman_wrapper.sh" ]; then
    cp "$TOOLS_DIR/caveman_wrapper.sh" "$BIN_DIR/caveman_wrapper.sh"
    chmod +x "$BIN_DIR/caveman_wrapper.sh"
    echo "[setup-caveman] wrapper installed to $BIN_DIR/caveman_wrapper.sh"
fi

# Copy templates.
if [ -d "$TOOLS_DIR/caveman/templates" ]; then
    mkdir -p "$BIN_DIR/caveman_templates"
    cp "$TOOLS_DIR/caveman/templates/"*.txt "$BIN_DIR/caveman_templates/" 2>/dev/null || true
    echo "[setup-caveman] templates installed"
fi

echo "[setup-caveman] done"