#!/bin/sh

# Copyright (C) 2015-2025 Internet Systems Consortium, Inc. ("ISC")
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.


# This script is used for testing the ProcessSpawn utility class. This
# class is used to fork and execute a new process. It also allows for
# checking the exit code returned when the process terminates.
# The unit tests execute this script via ProcessSpawn class with
# different command line parameters to test the class functionality.
#
# In particular, they check if the class correctly records the exit code
# returned. The exit code returned is controlled by the caller. It is
# possible to explicitly specify the exit code to be returned using
# the command line options. It is also possible to specify that the
# exit code is "unique" for the process, so as the test can check
# that two distinct processes spawned by the same ProcessSpawn
# object may return different status code. The command line of this
# script also allows for forcing the process to sleep so as the
# test has much enough time to verify that the convenience methods
# checking the state of the process, i.e. process running or not.

# Exit with error if commands exit with non-zero and if undefined variables are
# used.
set -eu

exit_code=0

# The exit code of 32 is returned when no args specified.
if test "${#}" = 0; then
    exit_code=32
fi

while test "${#}" -gt 0; do
    option=${1}
    shift
    case ${option} in
        -p)
            exit_code=${$}
            ;;
        -e)
            exit_code=${1-}
            shift
            ;;
        -s)
            sleep "${1-0}"
            exit_code=12
            shift
            ;;
        -v)
            VAR_NAME=${1}
            shift
            VAR_VALUE=${1}
            shift
            EXPECTED=$(env | grep -E "^${VAR_NAME}=" || true)
            if ! test "${VAR_NAME}=${VAR_VALUE}" = "${EXPECTED}"; then
                exit_code=34
            else
                exit_code=56
            fi
            ;;
        *)
            exit_code=78
            ;;
    esac
done

exit "${exit_code}"
