#!/bin/bash
# install-guardian.sh — npm postinstall script
# Copies upgrade-guardian.sh to ~/.grix/bin/ (idempotent, won't overwrite existing)
# This ensures the guardian script exists on first install and survives npm upgrades.

set -e

GRIX_HOME="${GRIX_CONNECTOR_HOME:-$HOME/.grix}"
GUARDIAN_DEST="$GRIX_HOME/bin/upgrade-guardian.sh"

# Don't overwrite — user may have custom modifications
if [ -f "$GUARDIAN_DEST" ]; then
  exit 0
fi

# Locate source: INIT_CWD is set by npm to the package root during lifecycle scripts
GUARDIAN_SRC="${INIT_CWD:-$(dirname "$0")}/scripts/upgrade-guardian.sh"
if [ ! -f "$GUARDIAN_SRC" ]; then
  # Fallback: try relative to this script
  GUARDIAN_SRC="$(cd "$(dirname "$0")" && pwd)/upgrade-guardian.sh"
fi

if [ ! -f "$GUARDIAN_SRC" ]; then
  echo "grix-connector postinstall: guardian source not found, skipping" >&2
  exit 0
fi

mkdir -p "$GRIX_HOME/bin"
cp "$GUARDIAN_SRC" "$GUARDIAN_DEST"
chmod +x "$GUARDIAN_DEST"
