#!/bin/sh
#
# title:
#
#    test ...
#
# setup:
#
#   defaults [ name ]
#   ...
#   end
# 
#   common [ name ]
#   ...
#   end
#
#   input [ name ]
#   ...
#   end
#
#   descr [ name ]
#   ...
#   end
#
#   use name ...
#
# execution:
#
#   options ...
#
#   keys seq
#
#   error RE
#
# verification:
#
#   output [ name ]
#   ...
#   end
#
#----------------


run()
{
    [ -z "$com" ] || opt="$opt -c cache/$com"
    [ -z "$def" ] || opt="$opt -d cache/$def"
    [ -z "$inp" ] || opt="$opt -i cache/$inp"
    [ -z "$out" ] || opt="$opt -o tmp/output"
    [ -z "$dsc" ] || opt="$opt cache/$dsc"
    touch tmp/stdin
    ../src/scend $opt <tmp/stdin >tmp/stdout 2>tmp/stderr
}


flush()
{
    [ -d tmp ] || return
    if run; then
	if [ -z "$out" ]; then
	    if [ ! -f tmp/output ]; then
		echo PASSED
	    else
		echo FAILED
		echo Didn\'t expect to get output. Got
		cat -v tmp/output
		exit 1
	    fi
	else
	    if cmp -s tmp/output cache/$out; then
		echo PASSED
	    else
		echo FAILED
		echo output mismatch:
		diff -u tmp/output cache/$out
		exit 1
	    fi
	fi
    else
	echo FAILED
	echo Expected success
	if [ -f tmp/stdout ]; then
	    echo stdout:
	    cat tmp/stdout
	fi
	if [ -f tmp/stderr ]; then
	    echo stderr:
	    cat tmp/stderr
	fi
	exit 1
    fi
}


test()
{
    flush
    rm -rf tmp
    mkdir tmp
    def=""
    com=""
    inp=""
    opt=""
    dsc=""
    echo -n "$*: "
}


file()
{
    [ -d cache ] || mkdir cache
    name=${2:-$1_tmp}
    eval $1=$name
    eval type$name=$1
    rm -f cache/$name
    touch cache/$name
    while read line; do
	[ "$line" = end ] && break
	echo "$line" >>cache/$name
    done
}


defaults()
{
    file def $*
}


common()
{
    file com $*
}


input()
{
    file inp $*
}


descr()
{
    file dsc $*
}


use()
{
    if [ -z "`eval echo '$'type$1`" ]; then
	echo Unknown file \"$1\"
	exit 1
    fi
    file "`eval echo '$'type$1`" $1
}


options()
{
    opt="$1"
}


keys()
{
    echo $1 | tr '_#' ' \012' >>tmp/stdin
}


error()
{
    if run; then
	echo FAILED
	echo Expected error \($*\)
	exit 1
    fi
    if sed 1q <tmp/stderr | grep "$*" >/dev/null; then
	echo PASSED
	rm -rf tmp
    else
	echo FAILED
	echo Expected $*, got
	cat tmp/stderr
	exit 1
    fi
}


output()
{
    file out $*
}


rm -rf tmp
read line
echo "$line"
while read line; do
    if echo $line | grep '^#' >/dev/null; then : ; else $line; fi
done
flush
exit 0
