#!/usr/bin/env sh
#
# ----------------------------------------------------------------------------
#
# Copyright 2019 IBM Corporation
#
# 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.
#
# ----------------------------------------------------------------------------
#

set -eu

die() { echo "$*" >&2 ; exit 1 ; }

test=$(printenv test)
chop=$(printenv chop)
chopm=$(printenv chopmarks)
testbin=$(printenv testbin)
testdir=$(printenv testdir)
CHOPSTIX_OPT_PRELOAD_PATH=$(printenv cxtrace)

export CHOPSTIX_OPT_PRELOAD_PATH

test_run() {
    ver="$1" ; shift

    echo "> test-$test $* ($ver)"
    # shellcheck disable=SC2068
    timeout "$TIMEOUT" "$testbin" $@ > "output.$ver" || die "Error: test failed"
    echo "> test-$test $* ($ver) OK"
}

test_trace_function() {
    fun="$1" ; shift
    ver="$1" ; shift
    rm -rf "$CHOPSTIX_OPT_TRACE_DIR" "$CHOPSTIX_OPT_LOG_PATH"
    echo "> $chopm $testbin $fun"

    bpoints=$("$chopm" "$testbin" "$fun" | tr "\n" " ")
    echo "> timeout $TIMEOUT $chop trace $bpoints $testbin $*" 

    # shellcheck disable=SC2068,SC2086
    timeout "$TIMEOUT" "$chop" trace $bpoints "$testbin" $@ > "output.$ver" 
    echo "> chop run ok"
}

validate_output() {
    echo "> check output $1 $2"
    set +e
    diff -a -I '#.*' "output.$1" "output.$2"
    set -e
    diff -a -I '#.*' -q "output.$1" "output.$2"
    echo "> validate output ok"
}

export TIMEOUT=60s

# shellcheck disable=SC1090,SC1091
. "$testdir/trace.spec"
