#!/bin/sh
#
# Run git gc on all bare Git repositories under a particular path.
#
# Written by Russ Allbery <eagle@eyrie.org>
# Copyright 2009, 2017 Russ Allbery <eagle@eyrie.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

set -e

# Make sure we get reasonable programs.
PATH=/bin:/usr/bin

# The only argument is the root directory of the git repositories.
if [ -z "$1" ] || [ ! -d "$1" ]; then
    echo 'Usage: git-gc-all <root>' >&2
    exit 1
fi
path="$1"
shift

# Run git gc on all the repositories.
cd "$path"
for dir in $(find . -name '*.git' -type d -print); do
    (set -e; cd $dir && git --bare gc --quiet "$@")
done
exit 0

# Documentation.  Use a hack to hide this from the shell.  Because of the
# above exit line, this should never be executed.
DOCS=<<__END_OF_DOCS__

=for stopwords
Allbery gc git-gc-all

=head1 NAME

git-gc-all - Run git gc on all bare Git repositories under a path

=head1 SYNOPSIS

B<git-gc-all> I<path> [I<arg> ...]

=head1 DESCRIPTION

Find all Git repositories under I<path> by looking for directories ending in
C<.git> and run C<git gc> on each directory.  Any additional arguments given
on the command-line will be passed to C<git gc> along with C<--quiet> and
C<--bare>.

This is used to run C<git gc> on all Git repositories hosted on git.eyrie.org
once per month.  This will be too often for some repositories, but creating a
pack each month shouldn't be too bad.  I can always run C<git gc --aggressive>
once a year or something.  It's deployed as a separate script so that I can
easily run it as a non-root user using cron.

=head1 BUGS

This script is not robust against directory names ending in C<.git> and
containing whitespace under the provided I<path>.

=head1 SEE ALSO

git-gc(1)

=head1 AUTHOR

Russ Allbery <eagle@eyrie.org>

=cut

__END_OF_DOCS__
