#!/bin/bash
# GNU Bash is required for running this script.

# Copyright (c) 2005 Ognyan Kulev
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

roots="browser dom extensions/reporter netwerk 
	other-licenses/branding/firefox security/manager toolkit"

help () {
    echo "$0" LANGUAGE
    exit 1
}

pootle () {
    for pootle_prefix in /usr /usr/local; do
	script=$pootle_prefix/lib/python2.3/site-packages/translate/convert/$1
	if [ -r $script ]; then
	    shift
	    python $script "$@"
	    return 0
	fi
    done
    echo "Error: Cannot find pootle script '$1'."
    exit 1
}

if [ -z "$1" ]; then
    help
fi
lang="$1"

if [ ! -d l10n ] || [ ! -d mozilla ]; then
    echo "Error: No subdirectories 'l10n' and 'mozilla'"
    help
fi

for r in $roots; do

    for f in $(find mozilla/$r/locales/en-US -type f ! -path '*/CVS/*'); do

	no_mozilla_f=${f/#mozilla/}
	lang_f=l10n/$lang${no_mozilla_f/locales\/en-US\//}
	lang_d=$(dirname $lang_f)
	[ -d $lang_d ] || mkdir -p -v $lang_d

	if [ ${f%.dtd} != $f ] || [ ${f%.properties} != $f ]; then

	    [ -f $lang_f ] || cp -v $f $lang_f
	    po_f=$lang_f.po
	    pot_f=$lang_f.pot

	    if [ ${f%.dtd} != $f ]; then
		type=dtd
	    else
		type=prop
	    fi

	    ${type}2po --progress=none -t $f $lang_f $pot_f
	    [ -f $po_f ] || cp -v $pot_f $po_f
	    msgmerge -q $po_f $pot_f > $po_f.new
	    cmp -s $po_f $po_f.new || mv -v $po_f.new $po_f
	    po2${type} --progress=none -t $f $po_f $lang_f
	    rm $pot_f

	else
	    # Verbatim files
	    [ -f $lang_f ] || cp -v $f $lang_f

	fi

    done

done

