#!/bin/bash

if [[ "$1" =~ ^-h|--help$ ]]; then
    echo "Scans the current directory for any files whose names"
    echo "aren't referenced in another file"
    echo
    echo "USAGE: $0 [KNOWN_USED_FILES]"
    echo
    echo "Specifying a file containing a list of known used files"
    echo "will prevent those files from being reported as unused."
    echo "Otherwise, any file whose name is not mentioned will"
    echo "be reported."
    exit 1
fi

known_used_files="${1:-/dev/null}"

# Get basenames of all not-gitignored files in the current directory.
function all-basenames {
    # fd implicitly ignores .gitignored files, but you can probably
    # use find with a few excludes, if 'fd' is not available for you.
    if ! command -v fd &> /dev/null; then
        echo "Script requires 'fd' to function!"
        exit 1
    fi
    fd --type file | xargs -I %% basename %%
}

total=0
unused=0

>&2 echo "Scanning for unused files..."
>&2 echo

while read -r file; do
    ((total++))
    file_no_ext="$(echo "$file" | sed 's/\(.*\)\..*/\1/')"
    if ! grep -iFq "$file_no_ext" "$known_used_files" &&
        ! grep -RIsiFq -- "$file_no_ext"; then
        ((unused++))
        echo "$file"
    fi
done < <(all-basenames)

>&2 echo
>&2 echo "$unused/$total scanned files appear unused"
