#!/bin/bash

# This script ensures the given $PRINCIPAL jsonnet program's actors can be
# successfully brought up under --dryrun conditions.

set -eo pipefail

tmpdir=$(mktemp -d "${TMPDIR:-/tmp}/$(basename $0).XXXXXXXX")
trap "rm -rf \"${tmpdir}\"" EXIT

if [ ${#} -gt 3 ]; then
    EXTRA_RENDITION_OPTIONS_PATH="$1"
    shift 1
fi

extra_rendition_options_path=""
if [ -n "${EXTRA_RENDITION_OPTIONS_PATH}" ]; then
    extra_rendition_options_path="--extra_rendition_options_path=${EXTRA_RENDITION_OPTIONS_PATH}"
    echo "# Extra options path? ${extra_rendition_options_path}"
fi

if [ ${#} -gt 2 ]; then
    EXTRA_RENDITION_OPTIONS="$1"
    shift 1
fi

extra_rendition_options=""
if [ -n "${EXTRA_RENDITION_OPTIONS}" ]; then
    extra_rendition_options="--extra_rendition_options=${EXTRA_RENDITION_OPTIONS}"
    echo "# Extra options? ${extra_rendition_options}"
fi

if [ ${#} -gt 1 ]; then
    PRINCIPAL="$1"
    shift 1
fi

echo "# Rendition program: ${PRINCIPAL}"

if [ -z "${PRINCIPAL}" ]; then
    echo "No principal rendition program!"
    exit 1
fi

hardware_configs="${@}"
if [ -z "${hardware_configs}" ]; then
    echo "No hardware configurations!"
    exit 1
fi

echo "# ${#} Hardware Configurations: ${hardware_configs}"

for config in ${hardware_configs}; do
    echo "# Hardware config: $config"

    ZOOX_VEHICLE_CONFIG="../calibration/param/${config}.json" \
    ZOOX_ROBOT_NAME=${config} \
      rostask/rostask vehicle/orchestration/zsupervisor \
        --principal ${PRINCIPAL} \
        --dryrun \
        --stderrthreshold=0 \
        "${extra_rendition_options_path}" \
        "${extra_rendition_options}"
done
