#!/bin/bash

VERSION=$(cat VERSION)

function removeline()
{
	# remvoes first occurrance line if found

	str=$1
	file=$2
	
	linenr=$(grep -m 1 -n "$str" "$file" | sed -r -e "s/([[:digit:]]*)(:.*)/\1/")
	if [ "$linenr" != "" ]; then
		sed -r -i -e "$linenr d" "$file"
	fi
}

function po()
{
	filename=$(echo $1 | awk '{print tolower($0)}')-screenlet
	cd $1
	tmpname="/tmp/$(uuidgen)"
	res=`grep "^_ *= *screenlets.utils.get_translator(__file__)" "$1""Screenlet.py"`
	if [ "$res" != "" ]; then
		xgettext --add-comments --from-code=utf-8 --force-po --output="$tmpname" --package-name=indiv-screenlets --package-version=$VERSION *.py
		sed -n -e "/class *""$1""Screenlet"" *(.*) *:/,/__name__/ p" "$1""Screenlet.py" | sed -e "/class *""$1""Screenlet"" *(.*) *:/ i\
import screenlets
" | pygettext -o - -n -D -K --no-location - | grep "#, docstring" -B 1 -A 25 -m 1 | sed -e "s/#, docstring/#. TRANSLATORS: This is the description of ""$1""Screenlet/" | grep "msgstr \"\"" -B 25 -m 1 >> "$tmpname"

		# check if pot has changed at all
		if [ -e "po/$filename.pot" ]; then
			strip1="/tmp/$(uuidgen)"
			strip2="/tmp/$(uuidgen)"
			cp "$tmpname" "$strip1"
			cp "po/$filename.pot" "$strip2"
			
			str="^\"POT-Creation-Date:.*[[:digit:]].*\\\n\"$"
			removeline $str $strip1
			removeline $str $strip2
			str="^\"Language:.*\\\n\"$"
			removeline $str $strip1
			removeline $str $strip2
			str="^\"Report-Msgid-Bugs-To:.*\\\n\"$"
			removeline $str $strip1
			removeline $str $strip2

			res=`diff -q $strip1 $strip2`
		else
			res="changed"
		fi
		
		echo $res

		if [ "$res" != "" ]; then
			# more than just a date has changed
			mkdir -p po
			echo "*** $filename.pot"
			cp "$tmpname" "po/$filename.pot"
		else
			notprinted=true
		fi

		cd po
		#pwd
		for x in $(ls *.po 2>/dev/null)
		do
			# check if po has changed and not just the position of Language field
			cp "$x" "$strip1"
			cp "$x" "$strip2"
			# to indicate which screenlet is being processed if pot is not created
			if $notprinted; then
				echo "--- $filename"
				notprinted=false
			fi
			echo -n "$x: "
			msgmerge -v --update "$strip2" "$filename.pot"
			potemp="/tmp/$(uuidgen)"
			cp "$strip2" "$potemp"

			str="^\"POT-Creation-Date:.*[[:digit:]].*\\\n\"$"
			removeline $str $strip1
			removeline $str $strip2
			str="^\"Language:.*\\\n\"$"
			removeline $str $strip1
			removeline $str $strip2
			str="^\"Report-Msgid-Bugs-To:.*\\\n\"$"
			removeline $str $strip1
			removeline $str $strip2

			res=`diff -q $strip1 $strip2`
			if [ "$res" != "" ]; then
				# more than just a date has positon of Language field has changed
				mv "$potemp" "$x"
			fi
		done

		rm -f "$tmpname"
		rm -f "$strip1"
		rm -f "$strip2"
		rm -f "$potemp"
		cd ..

	fi

	cd ..
#	echo "-------------------------------------------------"
#	exit
}

cd src
for x in $(find * -maxdepth 0 -mindepth 0 -type d)
do
#	echo -n "$x: "
	po "$x"
done
