#!/bin/bash

set -e
exec 2>&1

oneTimeSetUp() {
    # very basic lexer
    # see https://fbb-git.gitlab.io/flexcpp/manual/flexc++01.html#l4
    cat > ${SHUNIT_TMPDIR}/lexer <<EOF1
%%
[_a-zA-Z][_a-zA-Z0-9]*		return 1;
.|\n				// ignore
EOF1

    # driver for our lexer
    cat > ${SHUNIT_TMPDIR}/testflex.cc <<EOF2
#include <iostream>
#include "Scanner.h"

using namespace std;

int main()
{
    Scanner scanner;
    while (scanner.lex()) {
        cout << scanner.matched() << " ";
    }
    cout << "\n";
    return 0;
}
EOF2

    # some input for our lexer
    cat > ${SHUNIT_TMPDIR}/input <<EOF3
a b c
//
01 2 3.14159
#
X YY ZZZ
EOF3
}

#
# test steps must run in order
#

test01GenerateScanner() {
  cd ${SHUNIT_TMPDIR}
  flexc++ ${SHUNIT_TMPDIR}/lexer

  for f in lex.cc Scannerbase.h Scanner.h Scanner.ih
  do
    if [ ! -f "${SHUNIT_TMPDIR}/${f}" ]; then
      fail "flexc++ output file missing: ${f}"
    fi
  done
}

test02Compilation() {
  cd ${SHUNIT_TMPDIR}
  g++ *.cc -lbobcat -o testflex

  if [ ! -f "${SHUNIT_TMPDIR}/testflex" ]; then
    fail "compilation of textflex failed"
  fi
}

test03RunScanner() {
  local OUT=$(${SHUNIT_TMPDIR}/testflex < ${SHUNIT_TMPDIR}/input)
  assertNotSame "no output from scanner" "" "${OUT}"
  assertSame "unexpected output from scanner" "a b c X YY ZZZ " "${OUT}"
}

. shunit2
