#!/bin/sh
# Security pre-commit hook — runs checks inside Docker, no host installs required.
# Install: git config core.hooksPath .githooks

REPO_ROOT="$(git rev-parse --show-toplevel)"

# Resolve Docker socket — the git hook environment may not inherit the active
# Docker context, so we probe common socket paths explicitly.
if [ -S "/Users/$USER/.docker/run/docker.sock" ]; then
  export DOCKER_HOST="unix:///Users/$USER/.docker/run/docker.sock"
elif [ -S "/var/run/docker.sock" ]; then
  export DOCKER_HOST="unix:///var/run/docker.sock"
fi

# Collect staged files on the host and pass them into the container as arguments
STAGED=$(git diff --cached --name-only --diff-filter=ACM)

if [ -z "$STAGED" ]; then
  echo "[pre-commit] no staged files — skipping security check."
  exit 0
fi

echo "[pre-commit] running security checks..."

# Pass staged file list via environment variable
docker run --rm \
  -v "$REPO_ROOT":/repo \
  -w /repo \
  -e STAGED_FILES="$STAGED" \
  -u 1001:1001 \
  -e PIP_DISABLE_PIP_VERSION_CHECK=1 \
  -e PIP_NO_CACHE_DIR=1 \
  python:3.12-slim \
  sh -c "python -m venv /tmp/venv && /tmp/venv/bin/pip install --quiet bandit && /tmp/venv/bin/python scripts/security_check.py"

EXIT_CODE=$?

if [ $EXIT_CODE -ne 0 ]; then
  echo "[pre-commit] commit blocked by security check."
  exit 1
fi

exit 0
