#!/bin/sh
# testagcl-run.sh - build with agcl and diff results
# usage: testagcl-run.sh crossrun agcl-executable src-dir good-dir syn-file

if [ $# != 5 ]; then 
    echo "Usage: $0 crossrun ag-executable src-dir good-dir syn-file" 1>&2
    exit 1
fi

if [ ! -x "$2" ]; then
    echo "$0: agcl executable $2 not found" 1>&2
    exit 1
fi

if [ ! -d "$3" -o ! -f "$3/$5" ]; then
    echo "$0: source dir and syntax file $3/$5 not found" 1>&2
    exit 1
fi

if [ ! -d "$4" ]; then
    echo "$0: good dir $4 not found" 1>&2
    exit 1
fi

CROSSRUN="$1"
AGCL="$2"
SRCDIR="$3"
GOODDIR="$4"
SYN="$5"

BASE=`echo "$SYN" | sed 's,\.syn$,,'`
DIFF="$BASE.diff"

if [ "x$CROSSRUN" != x ]; then
    #echo "$CROSSRUN" "$AGCL" "$SRCDIR/$SYN"
    "$CROSSRUN" "$AGCL" "$SRCDIR/$SYN" > $BASE.log 2>&1
else
    #echo "$AGCL" "$SRCDIR/$SYN"
    "$AGCL" "$SRCDIR/$SYN" > $BASE.log 2>&1
fi
echo "Exit $?" >> $BASE.log

rm -f "$DIFF"

for F in "$BASE".*; do
    SUFF=`echo "$F" | sed 's,.*\.,.,'`
    if [ $SUFF = ".syn" ]; then
	continue;
    fi
    case $SUFF in
	.h|.c|.cpp)
	    tr -d '\r' < "$F" | sed '
		s/^\(#ifndef [A-Z_][A-Z0-9_-]*_H\)_[0-9][0-9]*$/\1/
		s/^\(#define [A-Z_][A-Z0-9_-]*_H\)_[0-9][0-9]*$/\1/
		s,^\(#line [0-9][0-9]* "\)[^"]*[/\\]\([^"]*\.syn"\),\1\2,
		s|^\(/\* *Line [0-9]*, \).*[/\\]\(.*\.syn \*/\)$|\1\2|
		s,^\(#line \)[0-9]*\( "[^"]*"\),\1-\2,
		s|^\(/\* *Line \)[0-9]*, \(.* \*/\)$|\1-, \2|
		s,^\( \* File generated by:\).*$,\1 ...,
	    ' > "$F.new"
	    mv -f "$F.new" "$F"
	;;
	*.log)
	    tr -d '\r' < "$F" | sed '
		s,^.*[/\\]\('"$SYN"': \),\1,
		s,^.*[/\\]\('"$SYN"'([0-9][0-9]*-[0-9][0-9]*): \),\1,
	    ' > "$F.new"
	    mv -f "$F.new" "$F"
	;;
	*)
	;;
    esac
    diff -uN "$GOODDIR"/"$F" "$F" >> "$DIFF"
done

exit 0
