#!/usr/bin/env python

# Ucitava XML sa listom modula i za svaki direktorijum sa prevodima za UI menja
# LINGUAS datoteku ako postoji sr@Latn.po ili ne postoji sr@latin.po datoteka.
# Zatim pravi sr@latin.po od sr.po ako ne postoji i na kraju azurira ChangeLog
# pripremajuci sve za commit.
#

import os
import sys
import string
import urllib
import libxml2
import datetime
from stat import *

if len(sys.argv) < 3:
    print """
  Usage: %s <directory> <xml file or URL>

    Where directory is path to local SVN checkout and xml file is list of
    modules from damned-lies. Programs recode-sr-latin and svn must be
    present in path. Branch labels from XML file are ignored and current
    checkout is used.

    Example: %s ~/svn/gnome/ gnome-2-20.xml
     
""" % (sys.argv[0], sys.argv[0])
    sys.exit(0)
        
prefix = sys.argv[1]
today = datetime.date.today()

print 'Using directory %s' % prefix
print 'Fetching moduleset from damned-lies...'
xml = urllib.urlopen(sys.argv[2]).read()
modules = libxml2.parseMemory(xml, len(xml))
for url in modules.xpathEval('//module//domain[@id="po"]//svnpath'):
    path = url.content.split('/')
    module = path[0]

    if path[1]=='trunk':
        s = 1
    elif path[1]=='branches':
        s = 2
    else:
        raise RuntimeError('Unknown SVN branch for module %s' % module)

    # File paths
    path = os.sep.join([prefix, path[0]]+path[s+1:])
    sr = os.path.join(path,'sr.po');
    sr_latn = os.path.join(path,'sr@Latn.po')
    sr_latin = os.path.join(path,'sr@latin.po')
    linguas = os.path.join(path,'LINGUAS')
    changelog = os.path.join(path, 'ChangeLog')

    print 'Processing module %s' % module
    if os.path.isfile(sr):

        changed = []

        if os.path.isfile(linguas): 
            # If there is sr@Latn file or there is no sr@latin file we need to edit LINGUAS
            if os.path.isfile(sr_latn) or not os.path.isfile(sr_latin):
                print '   Removing sr@Latn, adding sr@latin to LINGUAS file'

                langf = open(linguas, 'r+')
                langs = langf.readlines()
                if('sr@Latn\n' in langs):
                    langs.remove('sr@Latn\n')
                if('sr@latin\n' not in langs):
                    langs.insert(langs.index('sr\n')+1,'sr@latin\n')
                langf.seek(0)
                langf.writelines(langs)
                langf.close()
                changed.append('LINGUAS')
        else:
            raise RuntimeError('Missing LINGUAS file %s' % linguas)

        # Create or update sr@latin
        update = True
        if not os.path.isfile(sr_latin):
            print '   Creating sr@latin'
#
# FIXME: This is using local stat call, so if somebody else make changes,
#        after SVN checkout it wont be correct. Comparision needs to be
#        done based on some other info.
#
#        else:
#            if os.stat(sr)[ST_MTIME] > os.stat(sr_latin)[ST_MTIME]:
#                print '   Updating sr@latin'
#            else:
#                update = False
#
        if update:     
            if os.system('recode-sr-latin < %s > %s' % (sr, sr_latin)) != 0:
                raise RuntimeError('recode-sr-latin returned with error while processing %s' % sr)
            changed.append('sr@latin.po')

        # Remove old sr@Latn
        if os.path.isfile(sr_latn):
            print '   Removing old sr@Latn'
            os.unlink(sr_latn)
            if(os.system('svn delete %s' % (sr_latn)) != 0):
                raise RuntimeError('svn delete returned with error while removing %s' % sr_latn)
            changed.append('sr@Latn.po')
        
        # Add entry to ChangeLog
        if os.path.isfile(changelog):
            if changed:
                print '   Adding ChangeLog entry'
                changelogf = open(changelog, 'r+')
                changes = changelogf.read()

                if len(changed)==1 and changed[0]=='sr@latin.po':
                    msg = 'Updated Serbian Latin translation'
                else:
                    msg = 'Conversion from sr@Latn to sr@latin'
                    
                changes = """
    %s  Goran Rakic  <grakic@devbase.net>

            * %s: %s.

    """ % (today.strftime("%Y-%m-%d")  ,string.join(changed,', '), msg) + changes
                changelogf.seek(0)
                changelogf.write(changes)
                changelogf.close()
        
    else:
        print '   Module is not translated to Serbian or checkout is missing.'
        
print 'Done.'

