#!/bin/sh
# 20140825/allfd
VERSION=0.0.7
PROGRAM_BASENAME=$(basename $0)
PROGRAM_PATH=$(dirname $0)
COMPARE=/tmp/foptxt2awk.cmp.$$
RESULT=/tmp/foptxt2awk.result.$$
ERROR_LOG=/tmp/foptxt2awk.error.$$
ROW_ERROR_LOG=/tmp/foptxt2awk.error.row.$$
MISSED_LOG=/tmp/foptxt2awk.missed.$$
MFF_EXIT=0
FILTER_OPTIONS="--verbose"
trap "exit 1"                   HUP INT PIPE QUIT TERM
trap "rm -f ${COMPARE} $RESULT $ERROR_LOG $MISSED_LOG $ROW_ERROR_LOG" EXIT

version() {
	echo "$PROGRAM_BASENAME version $VERSION" >&2
	exit
}
usage() {
	printf "Aufruf:\n $PROGRAM_BASENAME [ --show-stopped ] <Vergleichsziel> [<Vergleichsdatei>,...]\n"  >&2
	printf "Optionen:\n --show-stopped    auch gestoppte Zeilen werden an STDERR ausgegeben\n\n"  >&2
	echo "$PROGRAM_BASENAME version $VERSION" >&2
}
usage_and_exit(){
	usage
	exit $1
}
error() {
	printf "$@\n" 1>&2
	usage_and_exit 1
}
machwas() {
	while read screen 
	do
		if echo "$screen" | grep -q '^[[:space:]]*[#].*'
		then
			continue
		fi
		${PROGRAM_PATH}/fopfilter -- $FILTER_OPTIONS --exact-match --row "$screen" $target 1>> $RESULT 2>$ROW_ERROR_LOG
		result=$?
		if [ "$result" = "1" ]
		then
			if [ $MFF_EXIT -lt 2 ]
			then
				MFF_EXIT=2
			fi
			cat $ROW_ERROR_LOG >> $MISSED_LOG
		elif [ "$result" = "8" ]
		then
			if [ $MFF_EXIT -lt 8 ]
			then
				MFF_EXIT=8
			fi
			cat $ROW_ERROR_LOG >> $MISSED_LOG
		else
			if [ $result -gt 1 ]
			then
				MFF_EXIT=9
			fi
			cat $ROW_ERROR_LOG >> $ERROR_LOG
		fi
	done 
}
setOptions(){
	if echo "$@" | grep -q '\-\-show\-stopped';
	then
	       FILTER_OPTIONS="${FILTER_OPTIONS} --only-active"
	fi
}
isOption(){
	case "$1" in
	--show-stopped)
			return 0
			;;
	esac
	return 1
}
target=
setOptions "$@"
while [ -z "$target" -a $# -gt 0 ]
do
	if ! isOption "$1"
	then
		target="$1"
	fi
	shift
done
if [ -z "$target" ]
then
	error "Vergleichsziel fehlt."
fi
if [ ! -e "$target" ]
then
	error "$target nicht gefunden."
fi
while [ $# -gt 0 ] && isOption "$1"
do
	shift
done
#Input aus STDIN
if [ $# = 0 ]
then
	machwas
fi
#Vergleichsquelle Datei(en)
while [ $# != 0 ]
do
	if ! isOption "$1"
	then
		sed -e '/^[[:space:]]*[#].*/d' -e 's/\#.*//' $1 > $COMPARE
		machwas < $COMPARE
	fi
	shift
done	
sort -n $RESULT | uniq >&1
if [ -e $MISSED_LOG ]
then
	echo ================================================== >&2
	cat $MISSED_LOG | sort -n |uniq >&2
fi
if [ -e $ERROR_LOG ]
then
	cat $ERROR_LOG >&2
fi
exit $MFF_EXIT
