#!/bin/sh

. $(dirname $0)/adc.common-functions

[ -n "$ATTIC" ] || die "Error: ATTIC not set"
[ -d "$ATTIC" ] || mkdir $ATTIC
[ -n "$WATCHDIR" ] || die 'Error: WATCHDIR not set'
[ -d "$WATCHDIR" ] || die "Error: $WATCHDIR does not exist"

[ -z "$1" ] && die 'Error: Need a repo name'

get_rights_and_owner gitolite-admin
[ -z "$perm_write" ] && die "Error: You do not have permission to remove repositories"

ATTIC_SUFFIX=`date +%Y-%m-%d_%H:%M:%S`
EMPTYSHA1='0000000000000000000000000000000000000000'

repo="${1%.git}"
repofull=$GL_REPO_BASE_ABS/packages/$repo.git

[ -d $repofull ] || die "Error: repository $repofull doesn't exist"
newdir=$ATTIC/$repo
mkdir -p $newdir || die "Error: cannot create attic directory in $ATTIC"
[ -d $newdir/%$ATTIC_SUFFIX ] && die "Error: Directory with this timestap already exists"
echo "Repository removed by $GL_USER" > $repofull/.gitolite.down

( echo $GL_USER
  echo $1
  GIT_DIR=$repofull git for-each-ref  --format="%(objectname) $EMPTYSHA1 %(refname)" refs/heads/\*
  ) > "$WATCHDIR/$1.$$"

SPECSDIR=$(git config hooks.specsdir)
[ -n "${SPECSDIR%%/*}" ] &&  SPECSDIR="$HOME/$SPECSDIR"
if [ -d $SPECSDIR ]; then
    git --git-dir="$repofull" ls-tree --name-only -r refs/heads/master | grep '\.spec$' |\
        xargs -I file rm "$SPECSDIR/file"
else
    echo "SPECSDIR $SPECSDIR is missing"
fi

mv $repofull $newdir/$ATTIC_SUFFIX
$HOME/bin/pldgithub.py delete $repo
