#!/bin/bash

# ICON
#
# ---------------------------------------------------------------
# Copyright (C) 2004-2026, DWD, MPI-M, DKRZ, KIT, ETH, MeteoSwiss
# Contact information: icon-model.org
# See AUTHORS.TXT for a list of authors
# See LICENSES/ for license information
# SPDX-License-Identifier: BSD-3-Clause
# ---------------------------------------------------------------

#-----------------------------------------------------------------------------
check_final_status()
{
    # Check if the first parameter (return status) is not OK
    # Arguments:
    #   $1 = error status: 0 = OK, not 0 = ERROR
    #   $2 = error message

    if [ "${current_status_file}" = "" ]
    then
      current_status_file=${basedir}/run/${job_name}.status
    fi
    if [ "${final_status_file}" = "" ]
    then
      final_status_file=${basedir}/run/${job_name}.final_status
    fi

    echo "$1" > $current_status_file
    echo "$1" > $final_status_file

    if [ $1 != 0 ]
    then
        echo "QSUBW_ERROR: JOB_%HOSTNAME%_%PID%: RC = "
        echo "check_error()"
        echo "   ERROR : $2"
        exit $1
    fi
}

check_error()
{
    # Check if the first parameter (return status) is not OK
    # Arguments:
    #   $1 = error status: 0 = OK, not 0 = ERROR
    #   $2 = error message
    if [ $1 != 0 ]
    then
      check_final_status $1 "$2"
    fi

    if [ "${current_status_file}" = "" ]
    then
      current_status_file=${basedir}/run/${job_name}.status
    fi

    echo "$1" > $current_status_file
}

warning()
{
    # Warning if the first parameter (return status) is not OK
    # Arguments:
    #   $1 = error status: 0 = OK, not 0 = ERROR
    #   $2 = error message
    if [ $1 != 0 ]
    then
        echo "   WARNING : $2"
    fi
}


number_of_required_files=0
number_of_linked_files=0

add_required_file()
{
  in_name=$1
  new_name=$2

  input_required_file[$number_of_required_files]=$in_name
  output_required_file[$number_of_required_files]=$new_name
  # print added required file $number_of_required_files ${input_required_file[${number_of_required_files}]} ${output_required_file[${number_of_required_files}]}
  (( number_of_required_files = number_of_required_files + 1 ))
}

print_required_files()
{
  i=0
  while [ $i -lt $number_of_required_files ]
  do
    print required file $i : ${input_required_file[${i}]} ${output_required_file[${i}]}
   (( i=i+1 ))
  done
}

copy_required_files()
{
  i=0
  while [ $i -lt $number_of_required_files ]
  do
    cp -f ${input_required_file[${i}]} ${output_required_file[${i}]}
   (( i=i+1 ))
  done
}

add_link_file()
{
  in_name=$1
  new_name=$2
  if [[ -d "$new_name" ]] ; then
    #In case the new_name is a directory, append the file name to the directory to form the effective path.
    new_name="${new_name%/}/${in_name##*/}"
  fi

  input_linked_file[$number_of_linked_files]=$in_name
  output_linked_file[$number_of_linked_files]=$new_name
  (( number_of_linked_files = number_of_linked_files + 1 ))
}

print_linked_files()
{
  i=0
  while [ $i -lt $number_of_linked_files ]
  do
    print linked file $i : ${input_linked_file[${i}]} ${output_linked_file[${i}]}
   (( i=i+1 ))
  done
}

link_required_files()
{
  i=0
  while [ $i -lt $number_of_linked_files ]
  do
    rm -f ${output_linked_file[${i}]}   # remove in order to replace the link if necessary
    ln -s ${input_linked_file[${i}]} ${output_linked_file[${i}]}
   (( i=i+1 ))
  done
}


get_2digits()
{
  local in=$1
  local outname=$2

  if [ $in -lt  10 ] ; then
    local f2dig=0$in
  else
    local f2dig=$in
  fi

 eval $outname=$f2dig
}

make_and_change_to_experiment_dir()
{
  # change working directory to experiment directory
  # create experiment directory if it does not exist
  #
  # environment variables used:
  # input:
  #   experiments_dir: the place where individual folders for each experiment will be created
  #   EXPNAME: string identifier of this experiment
  # output:
  #   EXPDIR
  #
  # experiment directory, with plenty of space, create if new
  EXPDIR="${experiments_dir}/${EXPNAME}"
  if [ ! -d "${EXPDIR}" ] ;  then
    mkdir -p "${EXPDIR}"
  fi

  ls -ld "${EXPDIR}"
  check_error $? "${EXPDIR} does not exist?"

  cd "${EXPDIR}"
}

compare_output_files()
{
  # Compare two output files with cdo.
  #
  # Usage: compare_output_files <file1> <file2>
  # Return: 0 if both files have the same content (according to cdo diffn)
  #
  # Environment variable `cdo` can be used to specify the cdo binary.

  FILE1=$1
  FILE2=$2
  if [[ ! -s "$FILE1" ]]; then
    echo "no such file '${FILE1}'."
    echo "Usage:  compare_output_files  FILE1 FILE2"
    return 1
  fi
  if [[ ! -s "$FILE2" ]]; then
    echo "no such file '${FILE2}'."
    echo "Usage:  compare_output_files  FILE1 FILE2"
    return 1
  fi

  # Please note that the exit status of 'cdo diffn' has changed with cdo 1.9.6.
  #   cdo version >= 1.9.6: "Exit status is 0 if inputs are the same and 1 if they differ"
  #   cdo version <  1.9.6: "Exit status is 1, if 'cdo diffn' fails and 0 otherwise"
  # Thus we cannot rely on the return value but have to check the stdout.
  set +e
  # use silent mode (-s) to suppress most output
  diffn_output="$(${cdo:-cdo} -s diffn "${FILE1}" "${FILE2}")"
  cdo_exitstat=$?
  set -e

  if [[ $cdo_exitstat -eq 0 ]] && [[ -z "$diffn_output" ]]; then
    echo " File 1 and file 2 are identical."
    echo " - file 1: ${FILE1}"
    echo " - file 2: ${FILE2}"
    return 0
  fi

  # verbose difference:
  ${cdo:-cdo} diffn "${FILE1}" "${FILE2}"
  echo " File 1 and file 2 differ or cdo failed (cdo exit status: $cdo_exitstat)"
  echo " - file 1: ${FILE1}"
  echo " - file 2: ${FILE2}"
  return 1
}

add_comin_setup()
{
 if [ -n "$builder" ] && [ "$builder" == "rcl_nec" ]; then

        case "$basedir" in
             */VE )
                 hostdir="${basedir}/../VH/"
                 ;;
             */vector )
                 hostdir="${basedir}/../host/"
                 ;;
        esac

        for path in "$@"; do
            # THIS PATH DOES NOT FIT TOGETHER WITH "host" NOMENCLATURE IN DWD_NEC
            export LD_LIBRARY_PATH="${hostdir}/${path}:$LD_LIBRARY_PATH"
            export VE_LD_LIBRARY_PATH="${basedir}/${path}:$VE_LD_LIBRARY_PATH"
        done
elif [ -n "$builder" ]; then
        for path in "$@"; do
            export LD_LIBRARY_PATH="${basedir}/${path}:$LD_LIBRARY_PATH"
        done
fi
}

#-----------------------------------------------------------------------------
