#!/bin/bash

# This is the supervisor test script!

set -eux -o pipefail

# Check that the number of child processes of the supervisor is equal to an
# expected number.
checkNumberOfChildProcesses() {
    local expected=$1
    local found=$(ps -F --ppid ${pid} --no-headers | wc -l)

    if [ ${expected} != ${found} ]; then
        echo "ERROR: expected = ${expected} found = ${found}"
        kill -TERM ${pid}
        exit 1
    fi
}

om_command="vehicle/orchestration/tools/om --stderrthreshold=0"

ZOOX_VEHICLE_CONFIG=../calibration/param/vh6a_01.json
export ZOOX_VEHICLE_CONFIG

PRINCIPAL=vehicle/orchestration/supervisor_test.libsonnet

vehicle/orchestration/zsupervisor --principal ${PRINCIPAL} --stderrthreshold=0 &
pid=$!

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

# Wait for metrics report
${om_command} metrics

# Validate the output of the parameters report
${om_command} params > ${tmpdir}/parameters-report.json
diff -c2 ${tmpdir}/parameters-report.json vehicle/orchestration/supervisor_test-expected.json

# Check that no child processes are started yet
checkNumberOfChildProcesses 0

# Start the test group
${om_command} perform test_group

# Check that two processes are not performing
checkNumberOfChildProcesses 2

# Validate the output of the state report
${om_command} state #> ${tmpdir}/state-report.json

kill -HUP ${pid}
sleep 1
checkNumberOfChildProcesses 2

# Stop the test group
${om_command} standby test_group
sleep 1
checkNumberOfChildProcesses 0

# Validate the output of the state report
${om_command} state #> ${tmpdir}/state-report.json

sleep 2
kill -TERM ${pid}
wait $!
