#!/bin/sh
# Run the same test compiled with -fstack-cleaner / f-no-stack-cleaner
# and compare the output.

srcdir="$1"
bindir="$2"

cd "$srcdir"

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

assert() {
  if ! eval "$1"; then
    die "Assertion failed: $@"
  fi
}

# If we don't have timeout, fake it:
if ! which timeout > /dev/null; then
  timeout() {
    shift
    "$@"
  }
fi

run() {
  state=$1
  shift
  timeout 30s ${bindir:=.}/bugged1_liveness_cleaner_$state \
    ${srcdir:=.}/../../platforms/platform.xml \
    ${srcdir:=.}/deploy_bugged1_liveness.xml \
    "--log=root.fmt:[%10.6r]%e(%i:%P@%h)%e%m%n" \
    --cfg=contexts/factory:ucontext \
    --cfg=contexts/stack_size:256
  assert 'test $? = 134'
}

get_states() {
  echo "$1" | grep "Expanded pairs = " | sed "s/^.*Expanded pairs = //" | head -n1
}

RES_ON="$(run on 2>&1 1>/dev/null)"
RES_OFF="$(run off 2>&1 1>/dev/null)"

STATES_ON=$(get_states "$RES_ON")
STATES_OFF=$(get_states "$RES_OFF")

# Both runs finished:
assert 'test -n "$STATES_ON"'
assert 'test -n "$STATES_OFF"'

# We expect 21 visited pairs with the stack cleaner:
assert 'test "$STATES_ON" = 21'

# We expect more states without the stack cleaner:
assert 'test "$STATES_ON" -lt "$STATES_OFF"'
