#!/usr/bin/python3
# -*- coding: utf-8 -*-

#  Copyright © 2011-2013  B. Clausius <barcc@gmx.de>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.


import sys, os, re

def convert(source_filename, target_filename):
    with open(source_filename, 'rt', encoding='utf-8') as source:
        lines = source.readlines()
    re_field = re.compile(r'^(.*): (.+)$')
    with open(target_filename, 'wt', encoding='utf-8') as target:
        translation_comment = None
        dstlineno = 0
        for srclineno, line in enumerate(lines):
            match = re_field.match(line)
            field, value = match.groups() if match else (None, None)
            if field == 'Path':
                sep = value[0]
                formatstr = '_({!r})' if sep != '@' else '{!r}'
                values = []
                for v in value.split(sep):
                    if v:
                        if translation_comment and translation_key in re.split('\W+', v):
                            values.append(translation_comment)
                        v = formatstr.format(v)
                        values.append(v)
                value = '\n'.join(values)
                dstlineno += len(values)
                translation_comment = None
            elif line.strip().startswith('#'):
                translation_comment = line.strip()
                translation_key = translation_comment.strip('#').strip().split()
                if translation_key:
                    translation_key = translation_key[0]
                else:
                    translation_comment = None
                value = None
            else:
                translation_comment = None
                value = None
            if value is None:
                if dstlineno <= srclineno:
                    value = ''
                    dstlineno += 1
                else:
                    continue
            target.write(value)
            target.write('\n')
    
def main():
    if len(sys.argv) != 2:
        print('usage: {} scriptfile'.format(os.path.basename(sys.argv[0])))
        return 1
    filename = sys.argv[1]
    convert(filename, filename+'.py')
    
if __name__ == '__main__':
    sys.exit(main())


