#!/usr/bin/env bash

echo "[Starting subtest - $(date)]"

# These C tests don't conform to -Wall
unset CHPL_DEVELOPER

# Normalize $CHPL_HOME to fix problems with symbolic links
SAVE_HOME=$CHPL_HOME
export CHPL_HOME=`readlink -f $CHPL_HOME`
if [ "x$CHPL_HOME" = "x" ]
then
  export CHPL_HOME=$SAVE_HOME
fi

DIR=regexp/ferguson/ctests
CC=gcc
CXX=g++
DEFS=`$CHPL_HOME/util/config/compileline --includes-and-defines`
RSRC="$CHPL_HOME/runtime/src/qio"
RE2_INSTALL_DIR=$($CHPL_HOME/util/config/compileline --libraries | \
                  sed 's#^.*\('"$CHPL_HOME"'/[^ ]*/re2/install/[^/]*\)/.*$#\1#')
RE2INCLS=-I$RE2_INSTALL_DIR/include
RE2LIB="-L$RE2_INSTALL_DIR/lib -Wl,-rpath,$RE2_INSTALL_DIR/lib -lre2"

RE=`$CHPL_HOME/util/chplenv/chpl_regexp.py`
if [ "$RE" = "re2" ]
then
  echo "[Working on $DIR with RE2]"
else
  echo "[Skipping directory $DIR without RE2]"
  exit
fi

echo $DEFS | grep atomics/intrinsics
if [ $? -eq 0 ]
then
  echo "[Working on $DIR with atomics/intrinsics]"
else
  echo "[Skipping directory $DIR without atomics/intrinsics]"
  exit
fi

# If we had an easy way to get the names of the C/C++ compilers
# we could support non-gnu
COMP=`$CHPL_HOME/util/chplenv/chpl_compiler.py --target`
PLAT=`$CHPL_HOME/util/chplenv/chpl_platform.py --target`
if [ "$COMP" = "gnu" ]
then
  echo C tests will run using gnu compiler
elif [ "$COMP" = "clang" ]
then
  echo C tests will run using clang compiler
  CC=clang
  CXX=clang++
else
  echo "[Skipping directory $DIR without gcc or clang]"
  exit
fi

DEPS="$OPTS --std=gnu++11 -Wall -DCHPL_RT_UNIT_TEST $DEFS $RE2INCLS"
LDEPS="$RSRC/qio.c $RSRC/sys.c $RSRC/sys_xsi_strerror_r.c $RSRC/qbuffer.c $RSRC/qio_error.c $RSRC/deque.c $RSRC/regexp/re2/re2-interface.cc $RE2LIB -lpthread"

T1="$CXX $DEPS -g regexp_test.cc -o regexp_test $LDEPS"
T2="$CXX $DEPS -g regexp_channel_test.cc -o regexp_channel_test $LDEPS"


dotest() {
  EXE=$1
  COMPLINE=$2
  start=$(date '+%s')
  echo "[test: $DIR/$EXE]"
  echo "[Executing compiler $COMPLINE]"
  $COMPLINE
  RETVAL=$?
  if [ $RETVAL -eq 0 ]
  then
    echo "[Success compiling $DIR/$EXE]"
    echo "[Executing program ./$EXE]"
    `$CHPL_HOME/util/test/timedexec 500 ./$EXE > /dev/null`
    RETVAL=$?
    if [ $RETVAL -eq 0 ]
    then
      echo "[Success matching program output for $DIR/$EXE]"

      rm ./$EXE
    elif [ $RETVAL -eq 222 ]
    then
      echo "[Error Timed out executing program $DIR/$EXE]"
    else
      echo "[Error matching program output for $DIR/$EXE]"
    fi
  else
    echo "[Error matching compiler output for $DIR/$EXE]"
  fi
  end=$(date '+%s')
  elapsed=$(($end - $start))
  echo "[Elapsed time to compile and execute all versions of \"$DIR/$EXE\" - ${elapsed}.0 seconds]"
}


dotest regexp_test "$T1"
dotest regexp_channel_test "$T2"

echo "[Finished subtest \"$DIR\" - $(date)]"
