#!/bin/sh
# Helper script to recompute error codes based on submodule
# Run from exchange/ main directory.
set -eu

# Generate taler-error-codes.h in gana and copy it to
# src/include/taler_error_codes.h
cd contrib/gana/gnu-taler-error-codes
make
cd ../../..
cat contrib/gana/gnu-taler-error-codes/taler_error_codes.h | sed -e "s/GNU_TALER_ERROR_CODES_H/GNU_ANASTASIS_ERROR_CODES_H/" -e "s/taler_error_codes.h/anastasis_error_codes.h/" > src/include/anastasis_error_codes.h

SRC_ROOT=$PWD

if [ ! -f $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

# 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
}


domake ()
{
    # $1 -- dir under contrib/
    dir="./contrib/$1"

    make -C $dir
}

ensure ()
{
    # $1 -- filename
    # $2 -- src dir under contrib/
    # $3 -- dst dir under ./
    fn="$1"
    src="./contrib/$2/$fn"
    tmp_dst="./$3/$fn.tmp"
    dst="./$3/$fn"

    cat $src | uncrustify -l c -c uncrustify.cfg > $tmp_dst
    if ! diff $tmp_dst $dst > /dev/null
    then
        test ! -f $dst || chmod +w $dst
        cp $tmp_dst $dst
        chmod -w $dst
    fi
    rm $tmp_dst
}

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
    cd contrib/gana || exit 1
    if [ ! -z "${COMMIT_HASH}" ]; then
      git checkout "${COMMIT_HASH}" || exit 1
      git pull
    fi
    cd $SRC_ROOT
    domake                     gana/gnu-taler-error-codes
    cat contrib/gana/gnu-taler-error-codes/taler_error_codes.h | \
        uncrustify -l c -c uncrustify.cfg | \
        sed -e "s/GNU_TALER_ERROR_CODES_H/GNU_ANASTASIS_ERROR_CODES_H/" -e "s/taler_error_codes.h/anastasis_error_codes.h/" > src/include/anastasis_error_codes.h
}

gana_update
