#!/bin/sh
# NB: should support repos checked out with --separate-git-dir!
# those have .git as a file containing something like
# gitdir: /path/to/git-dir

if [ ! -d ./.git/ ] ;then
	echo "Not a git repository (./.git/ is not a directory)"
	exit 0
fi

echo "> `du -hs ${PWD}/.git/`"

# use a bit of a hack to determine if our stamp exists and is the newest entry in .git
# (using grep to filter out the . and .. entries)
LASTFILE="`ls -1tra ./.git/ | grep -v '^\.[\.]*$' | tail -1`"
if [ "${LASTFILE}" = ".eradicated" ] ;then
	echo "Nothing changed since last `basename $0` - skipping"
	exit 0
fi

gfilter () {
	echo git filter-branch -f  --index-filter "git rm --force --cached --ignore-unmatch \"$1\"" -- --all
	git filter-branch -f  --index-filter "git rm --force --cached --ignore-unmatch \"$1\"" -- --all
}

for f in $@ ;do
	gfilter "$f"
done

rm -Rf .git/refs/original && \
    git reflog expire --expire=now --all && \
    git gc --aggressive && \
    git prune

date > .git/.eradicated
sync ; sleep 1 ; sync ; sleep 1
echo "< `du -hs .git/`" | tee -a .git/.eradicated
