#!/usr/bin/env bash
# scripts/install-kyverno-json.sh — install the kj CLI (v1.25, REQ-294;
# fixed v1.26 P3 W0.5).
#
# Installs the kyverno-json CLI via `go install` (D-115). The binary is a
# Go project — not a Python package. Cached via the Go module cache.
#
# v1.26 P3 W0.5 fix: the v1.25 script ran
#   go install github.com/kyverno/kyverno-json/cmd/kj@latest
# but the `cmd/kj` path does NOT exist in v0.0.3 — the upstream
# `go install github.com/kyverno/kyverno-json@latest` produces a binary
# named `kyverno-json`, NOT `kj`. The v1.25 invocation failed silently
# (the test suite masked it via `pytest.skip("kj not installed")`). This
# script now installs the real module and symlinks `kyverno-json` → `kj`
# so the engine's `which kj` check passes.
#
# Usage: bash scripts/install-kyverno-json.sh
# Exits 0 on success, 1 if Go is not installed, 2 if `kj version` fails.
set -euo pipefail

if ! command -v go >/dev/null 2>&1; then
  echo "ERROR: Go toolchain not found. Install Go (https://go.dev/dl/) first." >&2
  echo "       kyverno-json is a Go binary — \`go install\` is the upstream-blessed path (D-115)." >&2
  exit 1
fi

GOBIN="${GOBIN:-${HOME}/go/bin}"

# Idempotent: if kj is already on PATH and working, short-circuit.
if command -v kj >/dev/null 2>&1 && kj version >/dev/null 2>&1; then
  echo "kj installed:"
  kj version
  echo "DONE"
  exit 0
fi

echo "Installing kyverno-json CLI (kyverno-json) via go install..."
# The upstream module produces a binary named `kyverno-json` (NOT `kj`).
# The v1.25 `go install .../cmd/kj@latest` path does not exist in v0.0.3.
go install github.com/kyverno/kyverno-json@latest

# The binary is named `kyverno-json`, not `kj`. Symlink it as `kj` for
# the engine's `which kj` check (kyverno_json_engine.py::_which_kj).
if [ -x "${GOBIN}/kyverno-json" ] && ! command -v kj >/dev/null 2>&1; then
  ln -sf "${GOBIN}/kyverno-json" "${GOBIN}/kj"
  # If GOBIN not on PATH, try /usr/local/bin so `which kj` resolves.
  if ! command -v kj >/dev/null 2>&1; then
    ln -sf "${GOBIN}/kyverno-json" /usr/local/bin/kj 2>/dev/null || true
  fi
fi

if ! command -v kj >/dev/null 2>&1; then
  if [ -x "${GOBIN}/kyverno-json" ]; then
    echo "kyverno-json installed to ${GOBIN}/kyverno-json but 'kj' is not on PATH." >&2
    echo "add ${GOBIN} to PATH or symlink: ln -sf ${GOBIN}/kyverno-json /usr/local/bin/kj" >&2
    "${GOBIN}/kyverno-json" version
    exit 0
  fi
  echo "ERROR: kj not found on PATH after go install (checked ${GOBIN})." >&2
  exit 2
fi

echo "kj installed:"
kj version
echo "DONE"