# This is more portable than `which' but comes with
# the caveat of not(?) properly working on busybox's ash:
TALER_SRC_ROOT=$PWD
if [ ! -f $TALER_SRC_ROOT/contrib/gana_update.sh ]; then
  echo "Please run this script from the root of the taler source tree!"
  exit 1
fi

COMMIT_HASH=""
if [ ! -z $1 ]; then
  COMMIT_HASH=$1
fi

cleanup() {
    if [ -d $GANA_TMP ]; then
      rm -rf $GANA_TMP
    fi
    cd $TALER_SRC_ROOT
}

# This is more portable than `which' but comes with
# the caveat of not(?) properly working on busybox's ash:
existence()
{
    type "$1" >/dev/null 2>&1
}

gana_update()
{
    echo "Updating GANA..."
    if ! existence git; then
      echo "Script requires git"
      exit 1
    fi
    if ! existence recfmt; then
      echo "Script requires recutils"
      exit 1
    fi
    GANA_TMP=`mktemp -d`
    cd $GANA_TMP || exit 1
    git clone git://git.gnunet.org/gana.git
    cd gana || exit 1
    if [ ! -z "${COMMIT_HASH}" ]; then
      git checkout "${COMMIT_HASH}" || exit 1
    fi
    # Signatures
    echo "Updating Taler signatures"
    make taler_signatures.ts -C gnunet-signatures >/dev/null && \
       cp gnunet-signatures/taler_signatures.ts $TALER_SRC_ROOT/packages/taler-util/src/ || exit 1
    echo "GANA finished"
    cd $TALER_SRC_ROOT
}

trap cleanup EXIT
gana_update
