#!/bin/sh
set -u
script_dir=`dirname $0`
BUFRDC_TOOL=bufrdc_emoslib_bufr_filter
EMOSLIB_TOOL=emoslib_bufr_filter
ECCODES_TOOL=codes_bufr_filter
result=0 # return code from function
ERR_TOOL_NOT_FOUND=666

the_tool=$ECCODES_TOOL
is_emoslib=0

#########################################################
# Arguments:
#  arguments from the script command line
# Return Value:
#  the global variable 'result' holds the exit code
try_tool()
{
    if [ -f "${script_dir}/$the_tool" ]; then
        ${script_dir}/$the_tool "${@}"
        result=$?
    else
        if command -v $the_tool >/dev/null 2>&1; then
            $the_tool "${@}"
            result=$?
        else
            #echo "Could not find $the_tool. Return error"
            result=$ERR_TOOL_NOT_FOUND
        fi
    fi
}

#########################################################
# Deal with case where no arguments are provided e.g. usage
if [ $# -eq 0 ]; then
    # Give priority to ecCodes over emoslib
    the_tool=$ECCODES_TOOL
    try_tool "${@}"
    if [ $result -eq $ERR_TOOL_NOT_FOUND ]; then
        the_tool=$BUFRDC_TOOL
        try_tool "${@}"
    fi
    exit 0
fi

# Now process arguments. The "-i" switch is specific to emoslib
for i in "$@" ; do
   if [ "$i" = "-i" ]; then is_emoslib=1; fi
done

#########################################################
if [ $is_emoslib -eq 1 ]; then
    pkg='emoslib/bufrdc'
    the_tool=$EMOSLIB_TOOL
    try_tool "${@}"
    if [ $result -eq $ERR_TOOL_NOT_FOUND ]; then
        the_tool=$BUFRDC_TOOL
        try_tool "${@}"
    fi
else
    pkg='ecCodes'
    the_tool=$ECCODES_TOOL
    try_tool "${@}"
fi
if [ $result -eq $ERR_TOOL_NOT_FOUND ]; then
    echo "ERROR: Could not find the executable: $the_tool. Aborting!"  2>&1
    echo "       The arguments you passed in are relevant to $pkg." 2>&1
    echo "       Please make sure you have $pkg installed in your path."  2>&1
    exit 1
fi
exit $result
