#!/bin/sh
#
# Author: David Faure
#
# Concatenate ('merge') multiple .po files into a single .po file, for one language or for all of them
#
# Usage: $0i [-all] $outputfile <relative-paths-to-po-files>
#
# Example for one language: $0 bs/messages/koffice/kwordfilters.po bs/messages/koffice/*filter.po
#
# Example for all languages:
#  $0 -all messages/koffice/kwordfilters.po messages/koffice/kwordasciifilter.po messages/koffice/kwordlatexfilter.po

doall=0
if test "$1" = "-all"; then
  doall=1
  shift
fi

CDPATH=
outputfile="$1"
shift

concat()
{
  newpofile="$1"
  shift
  inputfiles=$*
  if test "$newpofile" != "$inputfiles"; then

    echo "Output file: $newpofile"
    echo "Input files: $inputfiles"

    dest=""
    if test -f "$newpofile"; then
      dest="$newpofile"
      echo -n "Initially, $newpofile: "
      msgfmt -o /dev/null --statistics $newpofile
    fi

    msgcat --to-code=UTF-8 --no-wrap --use-first $dest $inputfiles > out.tmp || exit 1
    mv -f out.tmp $newpofile

    relpath=`echo $newpofile | sed -e 's,^\./,,;s,^[^/]*/messages/,,'`  # remove language
    template="templates/${relpath}t"
    if test -f $template; then
      echo "Merging with template $template"
      ./merge.sh $newpofile $template || exit 1
      test -f $newpofile || exit 1
      echo -n "$newpofile: "
      msgfmt -o /dev/null --statistics $newpofile

      if test -n "$inputfiles"; then
        cvs rm -f $inputfiles
      fi
      if test -z "$dest"; then
        cvs add "$newpofile"
      fi
    else
      echo "No template found at $template"
    fi
  fi
}

if test $doall -eq 0; then
  concat $outputfile $*
else
  # For all languages
  find . -type d -maxdepth 1 -print | while read langdir; do
    langdir=`echo $langdir | sed -e 's,\./,,'`
    if test -d $langdir/messages; then
      if cd $langdir; then
        # Filter out the files that don't exist in this language
        files=`ls -1 $* 2>/dev/null | sed -e "s,^,$langdir/,"`
        cd ..
        if test -n "$files"; then
          concat $langdir/$outputfile $files
        fi
      fi
    fi
  done
fi
