#!/bin/bash

################################################################################
# Copyright 2023-2025 by NI SP Software GmbH, All rights reserved.
# Copyright 1999-2023 by Nice, srl., All rights reserved.
#
# This software includes confidential and proprietary information
# of NI SP Software GmbH ("Confidential Information").
# You shall not disclose such Confidential Information
# and shall use it only in accordance with the terms of
# the license agreement you entered into with NI SP Software.
################################################################################
################################################################################
. "${EF_ROOT}/plugins/torque/bin/common"


trim_spaces() {
    echo "$1" | sed 's/^ *//;s/ *$//'
}


emit_show_spooler() {
    case "${EF_OPT}" in
        -noredirect)
            "${EF_ROOT}/plugins/ef/bin/ef.show.spooler" "${EF_SPOOLER_URI}"
            ;;
        -silent)
            ;;
        *)
            echo "  <ef:redirect>$(ef_xml_escape_content -i "${REQUEST_URL_FIXED}?_uri=//com.enginframe.system/show.spooler&_spooler=$(ef_escape_uri_component "${EF_SPOOLER_URI}")")</ef:redirect>"
            ;;
    esac
}


# ---[ MAIN ]---------------------------------------------------------------- #

[ -n "${PARAMS}" ] && unset PARAMS
while [ -n "$1" ] ; do
  PARAMS="${PARAMS} \"$1\""
  shift
done

[ -z "${EF_SPOOLER_NAME}" ] \
  && EF_SPOOLER_NAME=`pwd`

# Cleanup EF_OPT and provide default value if missing
EF_OPT=`trim_spaces "${EF_OPT}"`
if [ -z "${EF_OPT}" ]; then
    if [ -n "${EF_WEBSERVICE_REQUEST}" ]; then
        EF_OPT='-noredirect'
    else
        EF_OPT='-redirect'
    fi
fi

output=`eval qsub ${PARAMS} 2>&1`

if [ $? -eq 0 ]
then
  if [ -n "${EF_SPOOLER_URI}" ]; then
    JOBID="`echo ${output} | "${EF_AWK}" '{print $1}'`"
    echo ${JOBID} >> .torquejobs
    emit_show_spooler
  else
    echo "<ef:output ${EF_XMLNS_ef}>"
    echo "${output}" | ef_xml_escape -p
    echo "</ef:output>"
  fi

  # Call service to fill the job cache with the new job
  "${EF_ROOT}/plugins/grid/bin/grid.jobcache.add.update.jobs" \
      --jobids "${JOBID}" \
      --grid "torque" \
      --cluster "${TORQUE_CLUSTER_ID}" \
      --spooler-uri "${EF_SPOOLER_URI}"

  _exit_code=0
else
  _command=`echo "qsub ${PARAMS}" | ef_xml_escape -p`
  _message=`echo "${output}" | ef_xml_escape -p`

  echo "<ef:error ${EF_XMLNS_ef}>"
  echo "  <ef:title>Submission failed</ef:title>"
  echo "  <ef:command>${_command}</ef:command>"
  echo "  <ef:message>${_message}</ef:message>"
  echo "</ef:error>"
  _exit_code=1
fi

if [ -n "${EF_SPOOLER_NAME}" -a -n "${EF_SPOOLER_URI}" ]; then
    "${EF_ROOT}/plugins/ef/bin/ef.spooler.info" "${EF_SPOOLER_URI}" "${EF_SPOOLER_NAME}"
fi

exit "${_exit_code}"

