# This is more portable than `which' but comes with
# the caveat of not(?) properly working on busybox's ash:
MAILBOX_SRC_ROOT=$PWD
if [ ! -f $MAILBOX_SRC_ROOT/contrib/gana_update.sh ]; then
  echo "Please run this script from the root of the 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 $MAILBOX_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+ssh://git@git.gnunet.org/gana.git || exit 1
    cd gana || exit 1
    if [ ! -z "${COMMIT_HASH}" ]; then
      git checkout "${COMMIT_HASH}" || exit 1
    fi
    # GNS
    echo "Updating Taler error codes"
    make -C gnu-taler-error-codes taler_error_codes.go  >/dev/null && \
       cp gnu-taler-error-codes/taler_error_codes.go $MAILBOX_SRC_ROOT/internal/gana/ || exit 1
    echo "Updating Taler signatures"
    make -C gnunet-signatures taler_signatures.go  >/dev/null && \
       cp gnunet-signatures/taler_signatures.go $MAILBOX_SRC_ROOT/internal/gana/ || exit 1

    echo "GANA finished"
    cd $MAILBOX_SRC_ROOT
}

trap cleanup EXIT
gana_update
