#!/bin/sh
set -e

getopt() { perl -ne "print \$1 if (m,/\* $1: (.*?) \*/, or m,// $1: (.*?)\n,)" $2; }

test -n "$PSQL" && ODBC="Driver={PostgreSQL};Database=divbench;Server=anna;ByteaAsLongVarBinary=1";
test -z "$ODBC" && ODBC="Driver=SQLITE;Database=/tmp/divbench.sqlite";

test -z "$B" && B=$(make show var=DEFAULT_FLAVOUR)
make $B-divbench 1>&2
exe=$(make show var=OBJ)$B/tools/divbench
import() { echo "$@"; $exe import "$@" -d "$ODBC"; }

wd=$PWD

find -L test/ -name \*.pkg | grep -v todo | while read f; do
    cp -R $f __pkg.$$
    cd __pkg.$$
    tag=$(echo $f | cut -d/ -f2 | sed -e s,ext-,,)
    name=$(echo $f | cut -d/ -f2-)
    f=$(basename $f)

    files=$(find . -type f -not -name script\* -exec echo --file '{}' \; | sed -e s,\./,,)
    scripts=
    test -e genscript.sh && bash ./genscript.sh
    test -e script && scripts=script
    for s in script.*; do test -e $s && scripts="$scripts $s"; done
    echo scripts: $scripts
    for s in $scripts; do
        variant=$(echo $s | sed -e s,script\.,, -e s,script,,)
        test -n "$variant" && variant="--variant $variant"
        import --name $name $variant $files --script $s --tag $tag
    done
    cd ..
    rm -rf __pkg.$$
done

find -L test -name \*.c -or -name \*.cpp | grep -v \.pkg/ | grep -v todo | while read f; do
    std=
    echo "$f" | grep -q '.cpp$' && std="-std=c++14"

    opts=$(eval echo $(getopt VERIFY_OPTS $f))
    args=$(eval echo $(getopt PROGRAM_OPTS $f))
    ccopt=$(eval echo $(getopt CC_OPTS $f))
    skipcc=$(getopt SKIP_CC $f)

    if test "$skipcc" = 1; then
        continue
    fi

    cd $(dirname $f)
    tag=$(echo $f | cut -d/ -f2 | sed -e s,ext-,,)
    name=$(echo $f | cut -d/ -f2-)
    f=$(basename $f)

    add=""
    for hdr in *.h*; do
        test -e $hdr && add="$add --file $hdr";
    done

    ( echo "cc -o testcase.bc $std $ccopt $f" ; echo "verify $opts testcase.bc $args" ) > script
    import --name $name --file $f $add --script script --tag $tag
    rm -f script
    cd $wd
done
