#!/usr/bin/env bash

# test that we can generate and run a basic model

if [ -z "${AUTOPKGTEST_TMP}" ]; then
  printf 'AUTOPKGTEST_TMP not set; not running in autopkgtest?\n' >&2
  exit 1
fi

set -e
set -x

# move to temporary directory
mkdir -p ${AUTOPKGTEST_TMP}/rumur-model
cd ${AUTOPKGTEST_TMP}/rumur-model

# temporarily allow failure so we can test some things
set +e

# check if the compiler supports -mcx16
cat - >mcx16-check.c <<EOT
int main(void) {
  return 0;
}
EOT
${CC:-cc} -std=c11 -mcx16 mcx16-check.c -o /dev/null
if [ $? -eq 0 ]; then
  MCX16=-mcx16
else
  MCX16=
fi

# check if we need libatomic support
cat - >libatomic-check.c <<EOT
#include <stdint.h>

int main(void) {
#if __SIZEOF_POINTER__ <= 4
  uint64_t target = 0;
#elif __SIZEOF_POINTER__ <= 8
  unsigned __int128 target = 0;
#endif
  return (int)__sync_val_compare_and_swap(&target, 0, 1);
}
EOT
${CC:-cc} -std=c11 ${MCX16} libatomic-check.c -o /dev/null
if [ $? -eq 0 ]; then
  LIBATOMIC=
else
  LIBATOMIC=-latomic
fi

# now disallow failure again
set -e

# construct a simple model
cat - >model.m <<EOT
var
  x: boolean;

startstate begin
  x := true;
end;

rule begin
  x := !x;
end;
EOT

# generate the checker for this model
rumur --output checker.c model.m

# compile it to an executable
${CC:-cc} -std=c11 ${MCX16} checker.c ${LIBATOMIC} -lpthread

# run the model to completion
./a.out
