#!/bin/sh -e
#
# git-rewrite-history - permanently delete files/folders from git repository
#
# ---
# source: https://github.com/unixorn/git-extra-commands/blob/main/bin/git-purge-from-history

usage() {
  printf '%s\n' "usage:${0##*/} [path/to/file] [path/to/folder]"
  exit 0
}

if [ "$#" -eq 0 ]; then
  usage
fi

if [ ! -d .git ]; then
  echo "Error: must run this script from the root of a git repository"
  exit 1
fi

# remove all paths passed as arguments from the history of the repo
files="$*"
git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch ${files}" HEAD

# remove temporary history git-filter-branch otherwise leaves behind for a long time
rm -rf .git/refs/original/ && git reflog expire --all && git gc --aggressive --prune
