#!/bin/bash

# staged_files_match - Check if any staged files match the provided glob patterns
#
# Usage: staged_files_match <pattern1> [pattern2] [...]
#
# Exits 0 (success) if at least one staged file matches any pattern
# Exits 1 (failure) if no staged files match any pattern
#
# Example:
#   staged_files_match './assert/**' './core/**/*.go' && go test ./core/...

set -e

# Check if at least one argument provided
if [[ $# -eq 0 ]]; then
  echo "Error: No glob patterns provided" >&2
  echo "Usage: $0 <pattern1> [pattern2] [...]" >&2
  exit 2
fi

# Get all staged files (including renamed files)
staged_files=$(git diff --cached --name-only --diff-filter=ACMR)

# If no staged files, exit with failure
if [[ -z "$staged_files" ]]; then
  exit 1
fi

# Check each glob pattern against each staged file
for pattern in "$@"; do
  # Remove './' prefix if present for consistent matching
  pattern="${pattern#./}"

  while IFS= read -r file; do
    # Remove './' prefix from file if present
    file="${file#./}"
 
    # Use case for glob matching
    case "$file" in
      $pattern)
        exit 0
        ;;
    esac
  done <<< "$staged_files"
done

exit 1
