#! /bin/sh

function check_xml() 
{
  if test -f $trans_doc; then
   case $trans_doc in
     */api/index.docbook) ;;
     */index.docbook|*/man-*.docbook)
       if ! meinproc --check --stdout $trans_doc > /dev/null; then
	  meinproc --check --stdout $trans_doc
          if test "$delete" -eq 1; then
            echo "RESTORING $trans_doc"
	    echo "RESTORING $trans_doc">>update_xml.log
            rm -f $trans_doc
	    svn revert $trans_doc	
          else
            echo "Failed on $trans_doc. Exiting."
            exit 1
          fi
       fi
       ;;
     *) ;;
   esac
  fi
}

LANG=C
LC_ALL=C
LC_MESSAGES=C

modules=`ls -1 documentation`
if test $# -eq 0 || test "$1" = "--help" ; then
  echo "update_xml [--nodelete] <lang_subdir> [selection]"
  exit
fi

delete=1
if test "$1" = "--nodelete"; then
  delete=0
  shift
fi

subdir=$1
selection=$2
if test -z "$selection"; then
   selection=*
fi

for m in $modules; do
   test -d documentation/$m || continue
	 
   files=`find documentation/$m -name "*.docbook"`

   if test -n "$files"; then
     for i in $files; do
	case $i in
	  *_original.docbook)
		continue
		;;
          *$selection*)
		;;
	  *)
 	    continue;;
	esac
	j=`echo $i | sed -e "s#documentation/$m/##" | sed -e 's#.docbook$##' | sed -e 's#/index$##' | sed -e "s#/#_#g"`
	translations=`ls -1 $subdir/docmessages/$m/$j.po 2>/dev/null`
	for t in $translations;	do
		bd=`dirname $t`
		p=`echo $i | sed -e "s#documentation/$m/##"`
		trans_doc="$bd/../../docs/$m/$p"
		dir=`dirname $trans_doc`
		result=`msgfmt -o /dev/null --statistics $t 2>&1`
                ret=$?
                if test $delete -eq 0 && test "$ret" -ne 0; then
                      echo "ERROR: msgfmt $t failed. Exiting."
                      exit 1
                fi
		if test "$ret" -ne 0 || echo $result | grep -q untranslated; then
		   echo "$t: $result"
	           continue
		fi
		if echo $result | grep -q fuzzy; then
	  	   echo "$t: $result" 
	           continue
		fi
		echo po2xml $i $t
		if ! po2xml $i $t > temp.xml; then
                   echo "ERROR: po2xml $i $t failed! Exiting!"
                   exit 1
                fi
		language=`cat $bd/../language `
		if test -n "$language"; then 
		   sed -e "s,<!ENTITY % English,<!ENTITY % $language," temp.xml > temp.xml.new
		   mv temp.xml.new temp.xml
		fi
		lang=$subdir
		if test ! -d $dir/.svn; then
			mkdir -p $dir
			rm -f $trans_doc
			mv temp.xml $trans_doc
			echo Makefile > ignore.$$
			echo Makefile.in >> ignore.$$
			echo Makefile.am >> ignore.$$
			svn add $dir
			svn ps svn:ignore -F ignore.$$ $dir
			rm ignore.$$
		else
			if ! cmp -s temp.xml $trans_doc; then
				:
				rm -f $trans_doc
				mv temp.xml $trans_doc
				if test "`svn status $trans_doc | cut -b-6`" = '?     ';  then
					svn add $trans_doc 
				fi
			else
				rm temp.xml
			fi
		fi
		check_xml
	done
     done
   fi
done

