#!/usr/bin/bash
#
# Copyright (C) 2022-2025 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

TOPDIR=$(cd $(dirname $0); pwd)

if [[ $0 =~ .*-podman$ ]]; then
    SUFFIX=-podman
else
    SUFFIX=
fi

if [ -r "$TOPDIR/common$SUFFIX" ]; then
    BASEDIR="$TOPDIR"
else
    BASEDIR=/usr/share/dci-pipeline
fi

. "$BASEDIR/common$SUFFIX"
DCI_QUEUE="$DEFAULT_QUEUE"

# get an optional dci-queue pool name with -p
if [ "$1" = "-p" ]; then
    shift
    DCI_QUEUE="$1"
    shift
fi

# get an optional dci-queue resource name with -r
if [ "$1" = "-r" ]; then
    shift
    export DCI_QUEUE_RESOURCE="$1"
    shift
fi

if [ -n "$DCI_QUEUE_RESOURCE" ]; then
    RES="$DCI_QUEUE_RESOURCE"
else
    RES="@RESOURCE"
fi

# set PATH for yaml2json
PATH=$BASEDIR:$PATH

CMD=()
OPTS=
NUM=2

# separate the dci-queue options from the dci-pipeline ones
while [ -n "$1" ]; do
    case "$1" in
        # transform -p <pool name> args into -e <pool name> and save
        # it in the OPTS variable for dci-queue and then replace them
        # with -p2, -p3, p4, etc.
        -p)
            OPTS="$OPTS -e $2"
            shift 2
            CMD+=( "-p${NUM}" )
            NUM=$((NUM + 1))
            ;;
        -*)
            OPTS="$OPTS $1"
            shift
            ;;
        *)
            CMD+=( "$1" )
            shift
            ;;
    esac
done

if [ -z "$DCI_QUEUE" ] || [ -n "$DCI_QUEUE_RESOURCE" ]; then
    CMD=( env DCI_QUEUE="${DCI_QUEUE}" RES="${RES}" "${BASEDIR}/dci-pipeline-helper${SUFFIX}" "${CMD[@]}" )
else
    CMD=( dci-queue schedule ${OPTS} "${DCI_QUEUE}" -- env DCI_QUEUE="${DCI_QUEUE}" RES="${RES}" KUBECONFIG="${KUBECONFIG}" "${BASEDIR}/dci-pipeline-helper${SUFFIX}" "${CMD[@]}")
fi

echo "+ ${CMD[*]}" 1>&2

exec "${CMD[@]}"

# dci-pipeline-schedule ends here
