#!/bin/bash
set -e

HOOK_DIR=".git/hooks"
HOOK_FILE="${HOOK_DIR}/pre-commit"

if [ ! -d ".git" ]; then
  echo "Error: .git directory not found. Run this from the repo root."
  exit 1
fi

echo "Installing pre-commit hook..."

cat > "${HOOK_FILE}" << 'EOF'
#!/bin/bash
# Auto-update CRDs if monitoring chart changes

CHART_DIR="k8s/monitoring/charts"
CRD_SCRIPT="scripts/update-crds.sh"
CRD_FILE="k8s/crds/all-crds.yaml"

# Check if chart directory has staged changes
if git diff --cached --name-only | grep -q "^${CHART_DIR}"; then
  echo "Monitoring chart changed. Updating CRDs..."
  
  if [ -f "${CRD_SCRIPT}" ]; then
    ./${CRD_SCRIPT}
    
    # Check if CRD file changed
    if git diff --name-only "${CRD_FILE}" | grep -q "${CRD_FILE}"; then
      echo "CRDs updated. Adding to commit..."
      git add "${CRD_FILE}"
    fi
  else
    echo "Warning: ${CRD_SCRIPT} not found. Skipping CRD update."
  fi
fi
EOF

chmod +x "${HOOK_FILE}"
echo "Pre-commit hook installed!"
