#!/bin/bash

# gitolite VREF to detect duplicate public keys

# see gitolite doc/virtual-refs.mkd for what the arguments are
sha=$3

# git sets this; and we don't want it at this point...
unset GIT_DIR

# paranoia
set -e

# setup the temp area
export TMPDIR=$GL_REPO_BASE_ABS
export tmp=$(mktemp -d -t gl-internal-temp-repo.XXXXXXXXXX);
trap "rm -rf $tmp" EXIT;

git archive $sha keydir | tar -C $tmp -xf -
    # DO NOT try, say, 'GIT_WORK_TREE=$tmp git checkout $sha'.  It'll screw up
    # both the 'index' and 'HEAD' of the repo.git.  Screwing up the index is
    # BAD because now it goes out of sync with $GL_ADMINDIR.  Think of a push
    # that had a deleted pubkey but failed a hooklet for some reason.  A
    # subsequent push that fixes the error will now result in a $GL_ADMINDIR
    # that still *has* that deleted pubkey!!

    # And this is equally applicable to cases where you're using a
    # post-receive or similar hook to live update a web site or something,
    # which is a pretty common usage, I am given to understand.

cd $tmp

for f in `find keydir -name "*.pub"`
do
    ssh-keygen -l -f "$f"
done | perl -ane '
    die "FATAL: $F[2] is a duplicate of $seen{$F[1]}\n" if $seen{$F[1]};
    $seen{$F[1]} = $F[2];
'

# as you can see, a vref can also 'die' if it wishes to, and it'll take the
# whole update with it if it does.  No messing around with sending back a
# vref, having it run through the matches, and printing the DENIED message,
# etc.  However, if your push is running from a script, and that script is
# looking for the word "DENIED" or something, then this won't work...
