#!/bin/bash
# openSUSE trunk and branch check for updates
#set localization code
loc="nl_NL.utf8"
# save the current directory
savedir=$(pwd)
# setup the language
lang="nl"
lyws="lcn yast webyast"
[ "$1" != "" ] && lyws="$1"
# find the trunk and branch directories
ldir=$(find ./ -name lcn)
[ "ldir" != "" ] || { echo "directories with trunk and/or branch not found" ; cd $savedir; exit 1 ;}
# check in all trunk and branch directories
for dir in $ldir; do
    echo "branch/trunk is: ${dir%/lcn}"
    for lyw in $lyws ; do
	cd $savedir
	[ -d ${dir%/lcn}/$lyw ] || { echo "$lyw directory not present" ; cd $savedir; continue ;}
	cd ${dir%/lcn}/$lyw
	echo "Now working in $(pwd)"
	# svn delete a .po file without a corresponding .pot file
	for file in $lang/po/*.po; do
	    # there are 3 pot directories 50-html, 00-pot and 50-pot, one of the last two must be present
	    [ -d *0-pot ] || { echo "Directory *0-pot with .pot files not present"; continue ; }
	    potfile=${file##$lang/po/}; potfile=${potfile%$lang.po}pot;
	    #[ -f *0-*/$potfile ] && echo "*0-*/$potfile found"
	    [ -f *0-*/$potfile ] || { svn delete $file; }
	done
	[ -d *0-pot ] || continue
	for pot in *0-pot/*.pot; do
	    # first check POT-Creation-Date, not equal means a merge
	    potrevpot=$(grep POT-Creation-Date $pot)
	    [ "$potrevpot" = "" ] && echo "$pot does not have a POT-Creation-Date:"
	    pofile="$lang/po/${pot##*/}"
	    pofile="${pofile%\.pot}.$lang.po"
	    # when .po file does not exist, it needs to be created
	    if [ ! -f $pofile ] ; then
		msginit --no-translator --locale=$loc --input=$pot --output=$pofile
		continue
	    fi
	    potrevpo=$(grep POT-Creation-Date $pofile)
	    [ "$potrevpo" = "" ] && echo "$pofile does not have a POT-Creation-Date:"
	    [ "$potrevpot" != "" ] && [ "$potrevpo" != "" ] && [  "$potrevpot" = "$potrevpo" ] && continue
	    # change date pofile newer than potfile -> no merge
	    [ "$potrevpo" = "" ] && [ $pofile -nt $potfile ] && continue
	    echo "msgmerge --previous --backup=none -U $pofile $pot"
	    [ "$potrevpot" != "" ] || [ "$2" != "" ] && msgmerge --previous --backup=none -U $pofile $pot
	done
	cd $savedir
    done
done
