#!/bin/sh
#
# gscr - scrub and pack Git repositories

# iterate through given directories; default to the current one
for arg in "${@:-.}"; do
  (
    # note the "exit" calls here in lieu of "continue" are deliberate; we're in
    # a subshell, so leaving it will continue the loop.

    # enter either bare repository or .git subdir
    case ${arg} in
      *.git)
        cd -- "${arg}" || exit
        ;;
      *)
        cd -- "${arg}"/.git || exit
        ;;
    esac

    # remove any original refs from a prior rewrite
    if [ -e refs/original ]; then
      rm -r -- refs/original || exit
    fi

    # check for bad references or other integrity/sanity problems
    git fsck --full --no-reflogs || exit

    # expire dangling references
    git reflog expire --all --expire=now --expire-unreachable=now || exit

    # remove dangling references
    git gc --prune=now --aggressive || exit

  )
done
