# -*- mode: sh; sh-shell: bash -*-
# vim: set ft=bash:
# shellcheck shell=bash

### Module for running tests in resource limited environments

declare -gx NICE_LEVEL="${NICE_LEVEL:-1}"            ## The nice level 'run_test' uses
declare -gx TIMEOUT_SECS="${TIMEOUT_SECS:-300}"      ## Timeout for tests
declare -gx MEMORY_KB="${MEMORY_KB:-33554432}"       ## Memory limit for tests

function run_test # [-n|--nice LEVEL] [-m|--memory KB] [-t|--timeout SECS] [program] [args..] - runs a test in a resource limited subshell
{
    while [[ $# -gt 0 ]]; do
        case "${1:-}" in
        -n|--nice)
            local NICE_LEVEL="$2"
            shift 2
            ;;
        -m|--memory)
            local MEMORY_KB="$2"
            shift 2
            ;;
        -t|--timeout)
            local TIMEOUT_SECS="$2"
            shift 2
            ;;
        *)
            break
            ;;
        esac
    done

    info "run_test $*"
    if (
        renice -n "$NICE_LEVEL" -p $BASHPID >/dev/null
        ulimit -S -v "$MEMORY_KB" -t "$TIMEOUT_SECS"
        "$@"
    ); then
        return 0
    else
        return 1
    fi
}
