#!/bin/sh
#
# Check for valid genesis syntax
# Rick van der Zwet, 2009
REPOS="$1"
TXN="$2"

TMPDIR=`mktemp -d -t $(basename $0 .sh)`

# Clean up
trap "rm -R $TMPDIR; exit 0" 0
trap "rm -R $TMPDIR; exit 1" 1 2 15

# External definition used for debugging
SVNLOOK="${SVNLOOK:-/usr/local/bin/svnlook --transaction $TXN}"
GENESISDIR='node-config/genesis'

# Check whether we need to check something first
$SVNLOOK changed $REPOS | grep -q $GENESISDIR
if [ $? -eq 1 ]; then
  exit 0
fi

echo "Checking genesis config, please hold your horses..." 1>&2
for ENTRY in `$SVNLOOK tree --full-paths $REPOS $GENESISDIR`; do
  echo $ENTRY | grep -q 'retired' && continue

  echo $ENTRY | grep -q '/$'
  if [ $? -eq 0 ]; then
    mkdir -p $TMPDIR/$ENTRY
  else
    $SVNLOOK cat $REPOS $ENTRY > $TMPDIR/$ENTRY
  fi
done

# Do actual checking
echo $TMPDIR/$GENESISDIR/tools/before-commit.sh 1>&2
sh $TMPDIR/$GENESISDIR/tools/before-commit.sh 2>> $TMPDIR/log.txt 1>>$TMPDIR/log.txt
RETVAL=$?

sed "s+$TMPDIR/node-config/genesis/nodes/++g" $TMPDIR/log.txt 1>&2

exit $RETVAL
