#!/usr/bin/env bash
# hook-wrapper.sh -- Universal wrapper that respects runtime controls
# Wraps any governance hook with profile checking and disable controls.
# Usage: hook-wrapper.sh <actual-hook.sh>
#
# Environment variables:
#   CXNI_HOOK_PROFILE     - minimal|standard|strict (default: standard)
#   CXNI_DISABLED_HOOKS   - comma-separated list of hook names to skip
#
# Part of @connexum/ai-governance

set -uo pipefail

# Get the actual hook to run
HOOK_SCRIPT="$1"
shift

if [ ! -f "$HOOK_SCRIPT" ]; then
  exit 0
fi

HOOK_NAME=$(basename "$HOOK_SCRIPT" .sh)

# Check if hook is explicitly disabled
if [ -n "${CXNI_DISABLED_HOOKS:-}" ]; then
  IFS=',' read -ra DISABLED <<< "$CXNI_DISABLED_HOOKS"
  for d in "${DISABLED[@]}"; do
    d=$(echo "$d" | xargs)  # trim whitespace
    if [ "$d" = "$HOOK_NAME" ]; then
      exit 0
    fi
  done
fi

# REMOVED: CXNI_MAINTENANCE_MODE bypass (security review 2026-04-17). Maintenance mode must not bypass enforcement.

# Check profile-based activation
PROFILE="${CXNI_HOOK_PROFILE:-standard}"

# Profile hierarchy: strict includes standard includes minimal
# Map hooks to minimum profile level
declare -A HOOK_PROFILES=(
  ["governance-file-shield"]="minimal"
  ["secret-leak-scanner"]="minimal"
  ["destructive-command-guard"]="minimal"
  ["web-access-gate"]="standard"
  ["audit-logger"]="standard"
  ["file-boundary-guard"]="strict"
  ["cost-budget-gate"]="strict"
  ["token-tracker"]="strict"
  ["file-change-tracker"]="strict"
  ["governance-integrity-check"]="minimal"
)

REQUIRED_PROFILE="${HOOK_PROFILES[$HOOK_NAME]:-standard}"

# Check if current profile includes this hook's required level
PROFILE_RANK=0
case "$PROFILE" in
  minimal) PROFILE_RANK=1 ;;
  standard) PROFILE_RANK=2 ;;
  strict) PROFILE_RANK=3 ;;
esac

REQUIRED_RANK=0
case "$REQUIRED_PROFILE" in
  minimal) REQUIRED_RANK=1 ;;
  standard) REQUIRED_RANK=2 ;;
  strict) REQUIRED_RANK=3 ;;
esac

if [ "$PROFILE_RANK" -lt "$REQUIRED_RANK" ]; then
  exit 0
fi

# Run the actual hook
exec "$HOOK_SCRIPT" "$@"
