#!/bin/bash

wypluwkaRoot=$1
rngRoot=$2

function getOptions {
	while getopts i:r: opt
	do
		case "$opt" in
			i) wypluwkaRoot=$OPTARG;;
			r) rngRoot=$OPTARG;;
			\?) echo "Invalid arguments!" 1>&2
				showHelp 1>&2
				exit 1;;
		esac
	done
}

function checkOptions {
	if [ "$wypluwkaRoot" == "" ]
	then
		echo "Missing input (wypluwka) dir"
		showHelp
		exit 1
	elif [ "$rngRoot" == "" ]
	then
		echo "Missing rng dir"
		showHelp
		exit 1
	fi
}

function showHelp {
	echo
	echo "Usage:"
	echo "validate -i <input_wypluwka_dir> -r <rng_dir>"
	echo "-i - input dir with wypluwka"
	echo "-r - dir with RelaxNG schemas"
	echo
}

function doValidate {
	what=$1
	for f in `find $wypluwkaRoot -name "ann_$what.*.xml" -o -name "ann_$what.xml" | sort`
	do
		echo "Validating $f"
		xmllint --xinclude --noout --relaxng $rngRoot/NKJP_$what.rng $f 2>/tmp/dupa
		if [ $? -ne 0 ]
		then
			wasError=1
			cat /tmp/dupa
			cat /tmp/dupa 1>&2
		fi
	done
}

function validate {
	doValidate "named"
	doValidate "groups"
	doValidate "words"
	if [ $wasError -ne 0 ]
	then
		echo "There were errors"
	else
		echo "Validation OK"
	fi
}

wasError=0
getOptions $*
checkOptions
validate

