#!/bin/bash -f

# Copyright © 2018-2023, Spillbox. All rights reserved.
# Property of Spillbox Inc.
# Any kind of copying or producing derivative work is prohibited without
# explicit written consent from Spillbox Inc.

usage()
{
    echo "Usage : multi_splrun splrun <cmd1> ++ splrun <cmd2> ++ .. <cmd n>" >&2
}

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
args=("$@")
n=${#args[@]}
i=0
while [ $i -lt $n ]
do
    cmd=${args[$i]}
    exe=$(basename $cmd)

    if [ "$exe" = "splrun" ]
    then
        i=$((i+1))
        subcmd=${args[$i]}

        # create a new subarray for each splrun command
        sublist=()

        while [ "$subcmd" != "++" ] && [ $i -lt $n ]
        do
            sublist+=("$subcmd")

            i=$((i+1))
            subcmd=${args[$i]}
        done

        # add the sublist to the list array
        list+=("[${sublist[*]}]")
    fi

    i=$((i+1))
done
# get the length of the list array
length=${#list[@]}
# join list elements with comma separator and wrap in square brackets
for (( i=0; i<$length; i++ ));
do
   str=$(echo "${list[$i]}" | tr -d '[]')
   echo "Invoking multi run support for the command: splrun $str"
   $DIR/splrun $str
   ret=$?
if [ $ret -eq 0 ]; then
    echo "Command succeeded"
else
    echo "Command failed with exit code $ret"
    exit $ret
fi
done

