#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#**************************************************************************
#*   Copyright (C) 2017 by S. MANKOWSKI / G. DE BURE support@mankowski.fr
#*   Redistribution and use in source and binary forms, with or without
#*   modification, are permitted provided that the following conditions
#*   are met:
#*   
#*   1. Redistributions of source code must retain the above copyright
#*      notice, this list of conditions and the following disclaimer.
#*   2. Redistributions in binary form must reproduce the above copyright
#*      notice, this list of conditions and the following disclaimer in the
#*      documentation and/or other materials provided with the distribution.
#*   
#*   THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
#*   IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
#*   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
#*   IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
#*   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
#*   NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#*   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#*   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#*   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
#*   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#**************************************************************************
# This script is based on l10n-fetch-po-files.py from GCompris and written by Trijita org <jktjkt@trojita.org>
import os
import re
import subprocess
import shutil

print("Downloading po. Please wait this can take time...")
SVN_PATH = "svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/"
SOURCE_PO_PATH = ["/messages/extragear-office/skrooge.po", "/docs/extragear-office/skrooge/index.docbook"]
OUTPUT_PO_PATH = "./po/"

fixer = re.compile(r'^#~\| ', re.MULTILINE)
re_empty_msgid = re.compile('^msgid ""$', re.MULTILINE)
re_empty_line = re.compile('^$', re.MULTILINE)
re_has_qt_contexts = re.compile('X-Qt-Contexts: true\\n')

if not os.path.exists(OUTPUT_PO_PATH):
    os.mkdir(OUTPUT_PO_PATH)

all_languages = subprocess.check_output(['svn', 'cat', SVN_PATH + 'subdirs'],
                                       stderr=subprocess.STDOUT).decode('utf-8')
all_languages = all_languages.split('\n')
all_languages.remove("x-test")
all_languages.remove("")
for lang in all_languages:
    try:
        lang_path = os.path.join(OUTPUT_PO_PATH, lang)
        if os.path.exists(lang_path):
            shutil.rmtree(lang_path)
        os.mkdir(lang_path)   
        
        for stp in SOURCE_PO_PATH:
            file_name = os.path.basename(stp)
            cmd = ['svn', 'cat', SVN_PATH + lang + stp]
            raw_data = subprocess.check_output(cmd, stderr=subprocess.PIPE).decode('utf-8')
            if file_name == "index.docbook":
                os.mkdir(os.path.join(lang_path, "docs"))
                os.mkdir(os.path.join(lang_path, "docs/skrooge"))
                
                file=open(os.path.join(os.path.join(lang_path, "docs/skrooge"), os.path.basename(stp)), "w")
                
                transformed = raw_data
                print("Fetched {}".format(lang))
            else:
                file=open(os.path.join(lang_path, os.path.basename(stp)), "w")
                
                (transformed, subs) = fixer.subn('# ~| ', raw_data)
                pos1 = re_empty_msgid.search(transformed).start()
                pos2 = re_empty_line.search(transformed).start()
                if re_has_qt_contexts.search(transformed, pos1, pos2) is None:
                    transformed = transformed[:pos2] + \
                            '"X-Qt-Contexts: true\\n"\n' + \
                            transformed[pos2:]
                    subs = subs + 1
                if (subs > 0):
                    print("Fetched {} (and performed {} cleanups)".format(lang, subs))
                else:
                    print("Fetched {}".format(lang))
                

        
            
            file.write(transformed)
            file.close
            print(file.name+" created")
    except subprocess.CalledProcessError:
        print("No data for {}".format(lang))
