#!/bin/sh

## Copyright (C) 2006-2013 Daniel Baumann <mail@daniel-baumann.ch>
##
## This program comes with ABSOLUTELY NO WARRANTY; for details see COPYING.
## This is free software, and you are welcome to redistribute it
## under certain conditions; see COPYING for details.


set -e

case "${1}" in
	--quiet)
		_QUIET="true"
		shift

		_GIT_REPACK_OPTIONS="-q"
		_GIT_GC_OPTIONS="--quiet"
		;;
esac

_REPOSITORIES="${@}"

if [ -z "${_REPOSITORIES}" ]
then
	if [ ! -e HEAD ]
	then
		_REPOSITORIES="*.git"
	else
		_REPOSITORIES="$(pwd)"
	fi
fi

for _REPOSITORY in ${_REPOSITORIES}
do
	[ "${_QUIET}" ] || echo "--------------------------------------------------------------------------------"
	[ "${_QUIET}" ] || echo ${_REPOSITORY}
	[ "${_QUIET}" ] || echo "--------------------------------------------------------------------------------"

	cd ${_REPOSITORY}
	git repack ${_GIT_REPACK_OPTIONS} -a -d -F && git gc ${_GIT_GC_OPTIONS} --aggressive --prune
	cd ..

	if [ "$(id -u)" -eq "0" ]
	then
		_UID="$(stat -c %u ${_REPOSITORY})"
		_GID="$(stat -c %g ${_REPOSITORY})"

		chown ${_UID}:${_GID} ${_REPOSITORY} -R
	fi
done
