#!/bin/sh

# little helper script for regenerating translation files. Mostly taken from cvs.sh from kde-autotool environment
# adapted to a cmake build environment and removed a lot not realy needed stuff
#EXTRACTRC=@EXTRACTRC@
#PREPARETIPS=@PREPARETIPS@
MESSAGES_DIR=@MESSAGES_DIR@
SOURCE_DIR=@CMAKE_SOURCE_DIR@
MAKE=make
POFILES="@POFILES@"
podir="${SOURCE_DIR}/po"


cd ${SOURCE_DIR}
rm -rf po.backup
mkdir po.backup

for i in `ls -1 po/*.pot 2>/dev/null | sed -e "s#po/##"`; do
  egrep -v '^#([^:]|$)' po/$i | egrep '^.*[^ ]+.*$' | grep -v "\"POT-Creation" > po.backup/$i
  cp po/$i po.backup/backup_$i
  touch -r po/$i po.backup/backup_$i
  rm po/$i
done

podir=${podir:-$PWD/po}
#files=`find . -name Makefile.am | xargs egrep -l '^messages:' `
#dirs=`for i in $files; do echo \`dirname $i\`; done`
dirs=${MESSAGES_DIR}
tmpname="$PWD/messages.log"
if test -z "$EXTRACTRC"; then EXTRACTRC=extractrc ; fi
if test -z "$PREPARETIPS"; then PREPARETIPS=preparetips ; fi
export EXTRACTRC PREPARETIPS

for subdir in $dirs; do
  test -z "$VERBOSE" || echo "Making messages in $subdir"
  (cd $subdir
   echo -e 'i18n("_: NAME OF TRANSLATORS\\n"\n"Your names")\ni18n("_: EMAIL OF TRANSLATORS\\n"\n"Your emails")' > _translatorinfo.cpp
   $EXTRACTRC `find . -name \*.ui -o -name \*.rc` > rc.cpp
   XGETTEXT="${XGETTEXT:-xgettext} -C -ki18n -ktr2i18n -kI18N_NOOP -ktranslate -kaliasLocale -x @KDE3_INCLUDE_DIR@/kde.pot"
   find . -name '*.cpp' | xargs ${XGETTEXT} _translatorinfo.cpp -o ${podir}/@PROJECT_NAME@.pot
   find . -name '*.ui.h' | xargs ${XGETTEXT} _translatorinfo.cpp -j -o ${podir}/@PROJECT_NAME@.pot
   ) 2>&1 | grep -v '^make\[1\]' > $tmpname
   test -s $tmpname && { echo $subdir ; cat "$tmpname"; }
   test -f $subdir/rc.cpp && rm -f $subdir/rc.cpp
   rm -f $subdir/_translatorinfo.cpp
done
rm -f $tmpname
for i in `ls -1 po.backup/*.pot 2>/dev/null | sed -e "s#po.backup/##" | egrep -v '^backup_'`; do
  test -f po/$i || echo "disappeared: $i"
done
for i in `ls -1 po/*.pot 2>/dev/null | sed -e "s#po/##"`; do
   msgmerge -q -o po/$i po/$i po/$i
   egrep -v '^#([^:]|$)' po/$i | egrep '^.*[^ ]+.*$' | grep -v "\"POT-Creation" > temp.pot
  if test -f po.backup/$i && test -n "`diff temp.pot po.backup/$i`"; then
	echo "will update $i"
	msgmerge -q po.backup/backup_$i po/$i > temp.pot
	mv temp.pot po/$i
  else
    if test -f po.backup/backup_$i; then
      test -z "$VERBOSE" || echo "I'm restoring $i"
      mv po.backup/backup_$i po/$i
      rm po.backup/$i
    else
      echo "will add $i"
    fi
  fi
done
rm -f temp.pot
rm -rf po.backup

echo Merging messages
for cat in $POFILES; do
  msgmerge -o $cat.new $cat @CMAKE_SOURCE_DIR@/po/@PROJECT_NAME@.pot
  if test -s $cat.new; then
    grep -v "\"POT-Creation" $cat.new > $cat.new.2
    grep -v "\"POT-Creation" $cat >> $cat.new.1
    if diff $cat.new.1 $cat.new.2; then
	rm $cat.new
    else
	mv $cat.new $cat
    fi
    rm -f $cat.new.1 $cat.new.2
  fi
done
