#!/bin/sh
# This script will synchronize language file with the master 
# english translation using chriskl's langcheck utility.
# It doesn't translate strings, only inserts english versions
# to proper positions and deletes removed. And it doesn't 
# synchronize commented lines. 
# You need to have GNU ed installed.
# 
# Usage: synch <language>
#
#   <language> is the filename without the .php extension
#
# WARNING!
#   I've tested it and it seems working fine. But I've not tested 
#   all combinations of input files lines, so use it at your own 
#   risk!
# 

if [ -z $1 ] ; then
	echo "You must tell me which language I should synchronize."
	echo -e "for example: \n\t$0 polish"
	exit
fi

if [ ! -f $1.php ] ; then
	echo "Sorry, I cannot find $1.php"
	exit
fi

echo "Making backup of $1.php"
cp $1.php $1.php.old

php langcheck $1 | awk '

function grep_n(what, where,   n, ln) {
# Returns "last occurance" line number
	n=1;	# current index
	ln=-1	# line number
	while ( (getline line < where ) > 0 ) {
		if (index(line, what)>0) {
	        	ln=n;
		}
		n++;
	}
	close(where);
	return ln;
}

function add_line(nr, where, what) {
	print nr"a\n"what"\n.\nw" | "/bin/ed -s "where
	system ("/bin/sync")
}

function del_line(nr, where) {
	print nr"d\nw" | "/bin/ed -s "where
	system ("/bin/sync")
}

BEGIN	    { line=1   }
# Analyse of "php langcheck language" output. 
# Chris - please, do not change those texts in langcheck :-)
/^Missing/  { oper="+" }
/^Deleted/  { oper="-" }
/^Source/   { src=$3   }
/^Target/   { trg=$3   }
/\$lang/    {
		split($1, a, "\\x27");
		# a[2] = strxxxxx
		# Adding a line
		if(oper=="+") {
			line = grep_n("\x27"a[2]"\x27", src) ;
			if (line>0) {
				add_line(line-1, trg, $0)
			}
		}
		# Deleting a line
		if(oper=="-") {
			line = grep_n("\x5B\x27"a[2]"\x27\x5D", trg);
			if (line>0) {
				del_line(line, trg)
			}
		}
	    }
' 
