#!/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/awsbatch/bin/common"
. "${EF_ROOT}/plugins/awsbatch/bin/aws.utils"

_ef_awsbstat_2xml () {
    _jobid_filter_in="$1"
    _jobid_filter_out="$2"

    "${EF_AWK}" \
        -v COMPRESS_ARRAY="${COMPRESS_JOB_ARRAY}" \
        -v GRID_TAG_SIZE_LIMIT="${GRID_TAG_SIZE_LIMIT}" \
        -v JOBID_FILTER_IN="${_jobid_filter_in}" \
        -v JOBID_FILTER_OUT="${_jobid_filter_out}" \
        -v "statusmap=${EF_ROOT}/plugins/awsbatch/conf/grid.job.status.mapping" \
        -f "${EF_ROOT}/plugins/ef/lib/awk/utils.awk" \
        -f "${EF_ROOT}/plugins/awsbatch/lib/awsbstat_2xml.awk"
}

# get simple jobs, array children and mnp children
_awsbstat_out="$(call_aws_ef_error awsbstat --cluster "${AWSBATCH_CLUSTER_ID}" --details --status=all --expand-children ${jobid} 2>&1)"
_exit_code="$?"

if [ "${_exit_code}" != "0" ]; then
    echo "${_awsbstat_out}"
    exit ${_exit_code}
fi

if [ -z "${jobid}" ]; then
    # call without --expand-children option to get mnp parent jobs
    _awsbstat_mnp_out="$(call_aws_ef_error awsbstat --cluster "${AWSBATCH_CLUSTER_ID}" --details --status=all 2>&1)"
    _exit_code="$?"

    if [ "${_exit_code}" != "0" ]; then
        echo "${_awsbstat_out}"
        exit ${_exit_code}
    fi
fi

echo "<grid:job-list type=\"awsbatch\" cluster=\"${AWSBATCH_CLUSTER_ID}\" ${EF_XMLNS_grid} >"
if [ -n "${_awsbstat_out}" ]; then
    # pass "" as jobid_filter_in parameter to get all children, except the ones filtered out
    # pass "[" as jobid_filter_out to remove parent jobs array from the output
    echo "${_awsbstat_out}" | _ef_awsbstat_2xml '' '['
fi
if [ -n "${_awsbstat_mnp_out}" ]; then
    # pass "*" as jobid_filter_in parameter to only get MNP jobs parent
    echo "${_awsbstat_mnp_out}" | _ef_awsbstat_2xml '*'
fi
echo "</grid:job-list>"

# vi: ts=4 sw=4 et syntax=sh :
