#!/bin/sh
#
# Check for valid genesis syntax
#
# Rick van der Zwet <rick@wirelessleiden.nl>
#
REPOS="$1"
TXN="$2"

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

# 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 -t $TXN $REPOS | grep -q $GENESISDIR
if [ $? -eq 1 ]; then
  exit 0
fi

# Allow us to commit stuff even if the validator fails
$SVNLOOK log -t $TXN $REPOS | grep -q 'no-genesis-check' && exit 0

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

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
