#!/bin/bash

#============================================================================
# Copyright 2016 ECMWF.
# This software is licensed under the terms of the Apache Licence version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.
#============================================================================

#
# DO NOT EDIT! SCRIPT PRODUCED BY make IN DIR ./scripts!
#
set -a
#set -x
#
# THIS FILE IS GENERATED BY cmake on 
#

INSTALLDIR=D:/bld/codes-ui_1570794650013/_h_env/Library
BUILDDIR=D:/bld/codes-ui_1570794650013/build
ECCODES_DIR=D:/bld/codes-ui_1570794650013/_h_env/Library/.
CODES_UI_ON_WINDOWS=true

CODES_UI_VERSION=prod

#Number of lines writen to stdout from log on error
TAILNUM=10

# app name
APP_NAME=$(basename $0)

# default file mode
FILE_TYPE=no

FILES_APPENDED=no
OUTPUT_REDIRECTED=no

# the pids of the running instances
EXE_PID_LST=

#-----------------------------------------------------------
# Setup dumps
#-----------------------------------------------------------

CODES_UI_BUFR_DUMP=${ECCODES_DIR}/bin/bufr_dump
CODES_UI_BUFR_FILTER=${ECCODES_DIR}/bin/bufr_filter
CODES_UI_BUFR_COPY=${ECCODES_DIR}/bin/bufr_copy
CODES_UI_GRIB_DUMP=${ECCODES_DIR}/bin/grib_dump

#----------------------------------------------------------------
# Windows Environment Settings
#----------------------------------------------------------------

if [ "$CODES_UI_ON_WINDOWS" = true ]; then
    # This path is added to %PATH% when activating the conda environment, but it
    # appears to be truncated to '/bin' by m2-bash on launching the shell. We
    # need it to be able to find the Qt dlls
    export PATH=$PATH:$CONDA_PREFIX/Library/bin
    # QT_PLUGIN_PATH needs to be set so we can find qwindows.dll
    export QT_PLUGIN_PATH=$CONDA_PREFIX/Library/plugins
fi

# ----------------------------------------------------------
# Clean up the tmp directory at the end or on error
#-----------------------------------------------------------

cleanup(){
    status=$?
    trap "" EXIT ERR

    if [ "$OUTPUT_REDIRECTED" = "yes" ]
    then
        exec 1>&5
        exec 2>&6
    fi

    echo ""
    if [ "$status" = "0" ]
    then
        if [ "$FILES_APPENDED" != "yes" ] ; then
            echo "${APP_NAME}: $1 (OK) (line $2), exit status $status, starting 'cleanup'"
        fi
    else
        echo "${APP_NAME}: $1 on ERROR (line $2), exit status $status, starting 'cleanup'"

        if [ x$CODES_UI_LOG != xyes ] ; then
            if [ -f $CODES_UI_LOGFILE ] ; then
                echo "Last $TAILNUM lines of log file:"
                tail -$TAILNUM $CODES_UI_LOGFILE
            fi
        fi
    fi

    #We only remove the tmpdir when we are sure that it belongs to codes_ui.
    #Rememeber: we redefine TMPDIR on startup!
    if [ $(echo $CODES_UI_DIR_TMP | grep -c "/codes_ui.") -ge 1 ] ; then
        rm -Rf $CODES_UI_DIR_TMP
    fi

    exit $status
}

check_exe() {

    exeType=$1
    exePath=$2

    if [ x"${exePath}" = x ] ; then
        print_error "$exeType executable is not defined"
        exit 1
    fi

    if [ ! -f $exePath ] ; then
        print_error "$exeType executable does not exist: " $exePath
        exit 1
    fi

    if [ ! -x $exePath ] ; then
        print_error "$exeType executable does not have execute permission: " $exePath
        exit 1
    fi
}

find_pids() {

    EXE_NAME=$(basename ${CODES_UI_EXE})

    lst=$(ps -C ${EXE_NAME}  o pid,user= | grep ${USER})
    for row in $lst ; do
        if [[ "$row" != "${USER}" ]] ; then
            EXE_PID_LST="$EXE_PID_LST $row"
        fi
    done
}

print_usage() {

cat <<HEND
NAME     ${APP_NAME}

USAGE    ${APP_NAME} [options] input_file(s)

OPTIONS
         -a   : add file(s) to a running instance of codes_ui (if found)
         -g   : GRIB mode
         -b   : BUFR mode
         -log : write log messages to standard output
         -h   : print this help message
HEND
}

print_error() {
    msg=$1
    echo -e "${APP_NAME}: \e[31mERROR: ${msg}\e[0m"
}

print_warning() {
    msg=$1
    echo -e "${APP_NAME}: \e[33mWARNING: ${msg}\e[0m"
}

print_red() {
    msg=$1
    echo -e "\e[31m${msg}\e[0m"
}

print_yellow() {
    msg=$1
    echo -e "\e[33m${msg}\e[0m"
}

case $CODES_UI_VERSION in

 dev)
    CODES_UI_DIR=$BUILDDIR
    ;;

 prod)
    CODES_UI_DIR=$INSTALLDIR
    ;;
esac

CODES_UI_DIR_SHARE=${CODES_UI_DIR}/share/codes_ui
CODES_UI_BIN=${CODES_UI_BIN:=$CODES_UI_DIR/bin}
CODES_UI_FILETYPE_EXE_NAME=codes_ui_file_type.x
CODES_UI_BUFR_EXE_NAME=codes_ui_bufr.x
CODES_UI_GRIB_EXE_NAME=codes_ui_grib.x
CODES_UI_FILETYPE_EXE=${CODES_UI_BIN}/${CODES_UI_FILETYPE_EXE_NAME}
CODES_UI_BUFR_EXE=${CODES_UI_BIN}/${CODES_UI_BUFR_EXE_NAME}
CODES_UI_GRIB_EXE=${CODES_UI_BIN}/${CODES_UI_GRIB_EXE_NAME}

#-----------------------------------------
# Check the exes and their directory
#-----------------------------------------

if [ ! -d $CODES_UI_BIN ] ; then
   print_error "exe dir does not exist"
   exit 1
fi

check_exe "fileType" ${CODES_UI_FILETYPE_EXE}
check_exe "BUFR" ${CODES_UI_BUFR_EXE}
check_exe "GRIB" ${CODES_UI_GRIB_EXE}

#-----------------------------------------------------------
# Prepare tmp dir
#-----------------------------------------------------------

#Define tmp root dir
TMPDIR_ROOT=${TMPDIR:=/tmp}

# check that TMPDIR_ROOT actually exists - we can't run without it
if [ ! -d $TMPDIR_ROOT ]
then
    echo ""
    echo "  Temporary directory '$TMPDIR_ROOT' does not exist"
    echo "  codes_ui needs this in order to run. Check that environment"
    echo "  variable \$TMPDIR is set to a valid directory and try again."
    exit 1
fi

#Define and create tmp dir
export CODES_UI_DIR_TMP=${TMPDIR_ROOT}/codes_ui.$$.$LOGNAME
mkdir -p $CODES_UI_DIR_TMP

#Check if we could create it
if [ $? -ne 0 ]
then
    echo ""
    echo "  Temporary directory '$CODES_UI_DIR_TMP' could not be created."
    echo "  codes_ui needs this in order to run. Check that environment"
    echo "  variable \$TMPDIR is set to a valid directory and try again."
    exit 1
fi

#Redefine TMPDIR
export TMPDIR=${CODES_UI_DIR_TMP}

# Where to write the log file to
export CODES_UI_LOGFILE=$CODES_UI_DIR_TMP/codes_ui_log_$$.$LOGNAME.txt

# Where the sockets should be saved for the -a option
export CODES_UI_SOCKETDIR=$TMPDIR_ROOT

#==============================================================
# tmp directory cleaned automatically at end or at error.
# on new platforms check that these signals are valid:
#==============================================================

CODES_UI_SIGLIST="HUP INT QUIT TERM XCPU  XFSZ"
#           1   2   3    15   30/24 31/25

trap 'cleanup "EXIT" $LINENO' EXIT
trap 'cleanup "SIGNAL trap" $LINENO' $CODES_UI_SIGLIST


#-----------------------------------------------------------
# Check the command line options
#-----------------------------------------------------------

checkoption() {

while [ "$1" != "" ]
do
    case "$1" in

        -g)
            FILE_TYPE=grib
            ;;

        -b)
            FILE_TYPE=bufr
            ;;

        -log)
            CODES_UI_LOG=yes
            ;;

        -h)
            CODES_UI_HELP=yes
            ;;

        -h)
            CODES_UI_HELP=yes
            ;;

        -a)
            CODES_UI_APPEND=yes
            ;;

         *)
            break
            ;;

    esac
    shift
done

IN_FILES="$*"

}

checkoption "$@"

#-----------------------------------------------------------
# Help message
#-----------------------------------------------------------

if [ "x$CODES_UI_HELP" != x ]
then
    print_usage
    exit 0
fi

#-------------------------------------------------------------
# Find out input file type
#-------------------------------------------------------------

if [ "$FILE_TYPE" = "no" ] ; then
    if [ x"$IN_FILES" = x ] ; then
        print_error "no input files were defined"
        echo
        print_usage
        exit 1
    fi

    #determine file mode
    FILE_TYPE_ERR_FILE=${CODES_UI_DIR_TMP}/file_type.err
    FILE_TYPE=$(${CODES_UI_FILETYPE_EXE} ${IN_FILES} 2> ${FILE_TYPE_ERR_FILE} )
    if [ $? -ne 0 ] ; then
        print_error "could not determine input file type!"
        if [ -s ${FILE_TYPE_ERR_FILE} ] ; then
            echo "Reason:"
            cat ${FILE_TYPE_ERR_FILE}
        fi
        exit 1
    elif [ -s ${FILE_TYPE_ERR_FILE} ] ; then
        echo "The file type was determined as $(echo $FILE_TYPE | tr /a-z/ /A-Z/) but warnings were generated:"
        print_yellow "$(cat ${FILE_TYPE_ERR_FILE})"
    fi
fi

#-------------------------------------------------------------
# Set executable and check filetype
#-------------------------------------------------------------

if [ "$FILE_TYPE" = "grib" ] ; then
    CODES_UI_EXE=$CODES_UI_GRIB_EXE
elif [ "$FILE_TYPE" = "bufr" ] ; then
    CODES_UI_EXE=$CODES_UI_BUFR_EXE
else
    print_error "input file type is invalid: ${FILE_TYPE}. File type must be GRIB or BUFR."
    exit 1
fi

#----------------------------------------------------------------
# Append mode - send message to the first available running instance
# to append/handle the specified input files
#----------------------------------------------------------------

if [ "$CODES_UI_APPEND" = "yes" ]
then
    find_pids

    for actPid in $EXE_PID_LST ; do
        SOC_NAME="codes_ui_${FILE_TYPE}_${actPid}"
        lds=${CODES_UI_SOCKETDIR}/${SOC_NAME}
        if [[ -S $lds ]] ; then
            echo add ${IN_FILES} | nc -U $lds
            if [ $? -eq 0 ] ; then
                FILES_APPENDED=yes
                exit 0
            else
                print_warning "failed to send message to socket ${lds}"
            fi
        fi
    done
    print_warning "could not add file(s) to a running instance. A new codes_ui instance will be started up."
fi

#----------------------------------------------------------------
# Check executable
#----------------------------------------------------------------

check_exe $(echo $FILE_TYPE | tr /a-z/ /A-Z/) ${CODES_UI_EXE}

#-----------------------------------------------------------
# Close tty and redirect stdout to a file?
#-----------------------------------------------------------

if [ x$CODES_UI_LOG != xyes ]
then
    exec  < /dev/null
    exec 5>&1                 # store for later
    exec 6>&2                 # store for later
    exec 1> $CODES_UI_LOGFILE # (restored in cleanup())
    exec 2>&1                 # redirect stderr to stdout, (restored in cleanup())
    OUTPUT_REDIRECTED=yes
fi

#----------------------------------------------------------------
#Run the executable!!!
#----------------------------------------------------------------

${CODES_UI_EXE} ${IN_FILES}
