#!/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.
################################################################################
################################################################################
################################################################################

#-------------------------------------------------------------------------------
# Load common EnginFrame functions and environment
#-------------------------------------------------------------------------------

. "${EF_ROOT}/plugins/ef/lib/functions"

ef_init_environment "$@"

#-------------------------------------------------------------------------------
# Load PBS Plug-in configuration
#-------------------------------------------------------------------------------

ef_source_conf pbs "ef.pbs.conf"
if [ -d "${PBS_BINDIR}" ] ; then
    PATH="${PBS_BINDIR}:${PATH}"
fi

which qstat >/dev/null 2>&1
if [ $? -ne 0 ] ; then
  ef_error "qstat not found" \
    "PBS binary directory is missing"
  exit 1
fi

#-------------------------------------------------------------------------------
# Check PBS is up and store cluster name
#-------------------------------------------------------------------------------

_qstat_out=$(qstat -B -f 2>&1)
_exit_code="$?"
if [ "${_exit_code}" != "0" ]; then
  ef_error "${_qstat_out} - exit code (${_exit_code})" \
    "EnginFrame PBS Plugin Error" \
    "qstat -B -f"
  exit ${_exit_code}
fi
PBS_CLUSTER_ID=$(echo "${_qstat_out}" | sed '/^Server: /!d;s/^Server[:] *//g')
[ -z "${PBS_CLUSTER_ID}" ] && PBS_CLUSTER_ID="default"
export PBS_CLUSTER_ID

QSTAT_CHECKS=$(qstat -H 2>&1)
QSTAT_CHECKS=`echo "${QSTAT_CHECKS}" | grep -i "PBS is not configured to maintain job history"`
if [ -n "${QSTAT_CHECKS}" ]; then
  ef_error "PBS is not correctly configured on your system.<br/>Please, contact your Administrator." \
    "PBS is not configured to maintain job history" \
    "qstat -H"
    exit 1
fi

#-------------------------------------------------------------------------------
# Load common PBS Plugin functions
#-------------------------------------------------------------------------------

. "${EF_ROOT}/plugins/pbs/bin/functions.lib.sh"

# ex:ts=4:sw=4:et:ft=sh:
