#!/bin/bash

GIT_DIR=$(git rev-parse --show-toplevel)

# Check if the file or any of its parent directories matches any patterns in gitignore
is_ignored_by_git() {
    # Check if the file is ignored using Git's own check-ignore command
    git -C "$GIT_DIR" check-ignore -q "$1"
    return $?
}

# Use the -print0 option with find to handle spaces in file names correctly
find "$GIT_DIR" -type f -size +50M -print0 | while IFS= read -r -d $'\0' FILE; do
    # Normalize path (remove leading GIT_DIR and './' from find)
    FILE="${FILE#"$GIT_DIR/"}"
    FILE="${FILE#./}"

    # If the file doesn't match any pattern in gitignore (and isn't ignored already), add it
    if ! is_ignored_by_git "$FILE"; then
        echo "Adding $FILE to .gitignore"
        echo "$FILE" >> "$GIT_DIR/.gitignore"
    fi
done
