#!/usr/bin/env python3
# updatetranslations.py
#
# tl;dr this script updates our translation file with the newest, coolest strings we've added!
# it manually searches the source code, extracts strings and then updates the language files.

# Written in 2018 by Daniel Oaks <daniel@danieloaks.net>
#
# To the extent possible under law, the author(s) have dedicated all copyright
# and related and neighboring rights to this software to the public domain
# worldwide. This software is distributed without any warranty.
#
# You should have received a copy of the CC0 Public Domain Dedication along
# with this software. If not, see
# <http://creativecommons.org/publicdomain/zero/1.0/>.

"""updatetranslations.py

Usage:
    updatetranslations.py run <irc-dir> <languages-dir>
    updatetranslations.py --version
    updatetranslations.py (-h | --help)

Options:
    <irc-dir>        Oragono's irc subdirectory where the Go code is kept.
    <languages-dir>  Languages directory."""
import os
import re
import json

from docopt import docopt
import yaml

ignored_strings = [
    'none', 'saset'
]

if __name__ == '__main__':
    arguments = docopt(__doc__, version="0.1.0")

    if arguments['run']:
        # general IRC strings
        irc_strings = []

        for subdir, dirs, files in os.walk(arguments['<irc-dir>']):
            for fname in files:
                filepath = subdir + os.sep + fname
                if filepath.endswith('.go'):
                    content = open(filepath, 'r', encoding='UTF-8').read()

                    matches = re.findall(r'\.t\("((?:[^"]|\\")+)"\)', content)
                    for match in matches:
                        if match not in irc_strings:
                            irc_strings.append(match)

                    matches = re.findall(r'\.t\(\`([^\`]+)\`\)', content)
                    for match in matches:
                        if match not in irc_strings:
                            irc_strings.append(match)

        for s in ignored_strings:
            try:
                irc_strings.remove(s)
            except ValueError:
                # ignore any that don't exist
                ...

        print("irc strings:", len(irc_strings))
        with open(os.path.join(arguments['<languages-dir>'], 'example', 'irc.lang.json'), 'w') as f:
            f.write(json.dumps({k:k for k in irc_strings}, sort_keys=True, indent=2, separators=(',', ': ')))
            f.write('\n')

        for string in irc_strings:
            if 1 < string.count('%s') + string.count('%d') + string.count('%f'):
                print('   confirm:', string)

        # help entries
        help_strings = []

        for subdir, dirs, files in os.walk(arguments['<irc-dir>']):
            for fname in files:
                filepath = subdir + os.sep + fname
                if fname == 'help.go':
                    content = open(filepath, 'r', encoding='UTF-8').read()

                    matches = re.findall(r'\`([^\`]+)\`', content)
                    for match in matches:
                        if '\n' in match and match not in help_strings:
                            help_strings.append(match)

        for s in ignored_strings:
            try:
                help_strings.remove(s)
            except ValueError:
                # ignore any that don't exist
                ...

        print("help strings:", len(help_strings))
        with open(os.path.join(arguments['<languages-dir>'], 'example', 'help.lang.json'), 'w') as f:
            f.write(json.dumps({k:k for k in help_strings}, sort_keys=True, indent=2, separators=(',', ': ')))
            f.write('\n')

        for string in help_strings:
            if 1 < string.count('%s') + string.count('%d') + string.count('%f'):
                print('   confirm:', string.split('\n')[0])

        # nickserv help entries
        help_strings = []

        for subdir, dirs, files in os.walk(arguments['<irc-dir>']):
            for fname in files:
                filepath = subdir + os.sep + fname
                if fname == 'nickserv.go':
                    content = open(filepath, 'r', encoding='UTF-8').read()

                    matches = re.findall(r'\`([^\`]+)\`', content)
                    for match in matches:
                        if match not in help_strings:
                            help_strings.append(match)

        for s in ignored_strings:
            try:
                help_strings.remove(s)
            except ValueError:
                # ignore any that don't exist
                ...

        print("nickserv help strings:", len(help_strings))
        with open(os.path.join(arguments['<languages-dir>'], 'example', 'nickserv.lang.json'), 'w') as f:
            f.write(json.dumps({k:k for k in help_strings}, sort_keys=True, indent=2, separators=(',', ': ')))
            f.write('\n')

        for string in help_strings:
            if 1 < string.count('%s') + string.count('%d') + string.count('%f'):
                print('   confirm:', string)

        # chanserv help entries
        help_strings = []

        for subdir, dirs, files in os.walk(arguments['<irc-dir>']):
            for fname in files:
                filepath = subdir + os.sep + fname
                if fname == 'chanserv.go':
                    content = open(filepath, 'r', encoding='UTF-8').read()

                    matches = re.findall(r'\`([^\`]+)\`', content)
                    for match in matches:
                        if match not in help_strings:
                            help_strings.append(match)

        for s in ignored_strings:
            try:
                help_strings.remove(s)
            except ValueError:
                # ignore any that don't exist
                ...

        print("chanserv help strings:", len(help_strings))
        with open(os.path.join(arguments['<languages-dir>'], 'example', 'chanserv.lang.json'), 'w') as f:
            f.write(json.dumps({k:k for k in help_strings}, sort_keys=True, indent=2, separators=(',', ': ')))
            f.write('\n')

        for string in help_strings:
            if 1 < string.count('%s') + string.count('%d') + string.count('%f'):
                print('   confirm:', string)

        # hostserv help entries
        help_strings = []

        for subdir, dirs, files in os.walk(arguments['<irc-dir>']):
            for fname in files:
                filepath = subdir + os.sep + fname
                if fname == 'hostserv.go':
                    content = open(filepath, 'r', encoding='UTF-8').read()

                    matches = re.findall(r'\`([^\`]+)\`', content)
                    for match in matches:
                        if match not in help_strings:
                            help_strings.append(match)

        for s in ignored_strings:
            try:
                help_strings.remove(s)
            except ValueError:
                # ignore any that don't exist
                ...

        print("hostserv help strings:", len(help_strings))
        with open(os.path.join(arguments['<languages-dir>'], 'example', 'hostserv.lang.json'), 'w') as f:
            f.write(json.dumps({k:k for k in help_strings}, sort_keys=True, indent=2, separators=(',', ': ')))
            f.write('\n')

        for string in help_strings:
            if 1 < string.count('%s') + string.count('%d') + string.count('%f'):
                print('   confirm:', string)

[((39, 16, 39, 48), 'docopt.docopt', 'docopt', (), '', False, 'from docopt import docopt\n'), ((45, 35, 45, 66), 'os.walk', 'os.walk', ({(45, 43, 45, 65): "arguments['<irc-dir>']"}, {}), "(arguments['<irc-dir>'])", False, 'import os\n'), ((80, 35, 80, 66), 'os.walk', 'os.walk', ({(80, 43, 80, 65): "arguments['<irc-dir>']"}, {}), "(arguments['<irc-dir>'])", False, 'import os\n'), ((110, 35, 110, 66), 'os.walk', 'os.walk', ({(110, 43, 110, 65): "arguments['<irc-dir>']"}, {}), "(arguments['<irc-dir>'])", False, 'import os\n'), ((140, 35, 140, 66), 'os.walk', 'os.walk', ({(140, 43, 140, 65): "arguments['<irc-dir>']"}, {}), "(arguments['<irc-dir>'])", False, 'import os\n'), ((170, 35, 170, 66), 'os.walk', 'os.walk', ({(170, 43, 170, 65): "arguments['<irc-dir>']"}, {}), "(arguments['<irc-dir>'])", False, 'import os\n'), ((69, 18, 69, 88), 'os.path.join', 'os.path.join', ({(69, 31, 69, 59): "arguments['<languages-dir>']", (69, 61, 69, 70): '"""example"""', (69, 72, 69, 87): '"""irc.lang.json"""'}, {}), "(arguments['<languages-dir>'], 'example', 'irc.lang.json')", False, 'import os\n'), ((70, 20, 70, 108), 'json.dumps', 'json.dumps', (), '', False, 'import json\n'), ((99, 18, 99, 89), 'os.path.join', 'os.path.join', ({(99, 31, 99, 59): "arguments['<languages-dir>']", (99, 61, 99, 70): '"""example"""', (99, 72, 99, 88): '"""help.lang.json"""'}, {}), "(arguments['<languages-dir>'], 'example', 'help.lang.json')", False, 'import os\n'), ((100, 20, 100, 109), 'json.dumps', 'json.dumps', (), '', False, 'import json\n'), ((129, 18, 129, 93), 'os.path.join', 'os.path.join', ({(129, 31, 129, 59): "arguments['<languages-dir>']", (129, 61, 129, 70): '"""example"""', (129, 72, 129, 92): '"""nickserv.lang.json"""'}, {}), "(arguments['<languages-dir>'], 'example', 'nickserv.lang.json')", False, 'import os\n'), ((130, 20, 130, 109), 'json.dumps', 'json.dumps', (), '', False, 'import json\n'), ((159, 18, 159, 93), 'os.path.join', 'os.path.join', ({(159, 31, 159, 59): "arguments['<languages-dir>']", (159, 61, 159, 70): '"""example"""', (159, 72, 159, 92): '"""chanserv.lang.json"""'}, {}), "(arguments['<languages-dir>'], 'example', 'chanserv.lang.json')", False, 'import os\n'), ((160, 20, 160, 109), 'json.dumps', 'json.dumps', (), '', False, 'import json\n'), ((189, 18, 189, 93), 'os.path.join', 'os.path.join', ({(189, 31, 189, 59): "arguments['<languages-dir>']", (189, 61, 189, 70): '"""example"""', (189, 72, 189, 92): '"""hostserv.lang.json"""'}, {}), "(arguments['<languages-dir>'], 'example', 'hostserv.lang.json')", False, 'import os\n'), ((190, 20, 190, 109), 'json.dumps', 'json.dumps', (), '', False, 'import json\n'), ((51, 30, 51, 78), 're.findall', 're.findall', ({(51, 41, 51, 68): '"""\\\\.t\\\\("((?:[^"]|\\\\\\\\")+)"\\\\)"""', (51, 70, 51, 77): 'content'}, {}), '(\'\\\\.t\\\\("((?:[^"]|\\\\\\\\")+)"\\\\)\', content)', False, 'import re\n'), ((56, 30, 56, 73), 're.findall', 're.findall', ({(56, 41, 56, 63): '"""\\\\.t\\\\(\\\\`([^\\\\`]+)\\\\`\\\\)"""', (56, 65, 56, 72): 'content'}, {}), "('\\\\.t\\\\(\\\\`([^\\\\`]+)\\\\`\\\\)', content)", False, 'import re\n'), ((86, 30, 86, 66), 're.findall', 're.findall', ({(86, 41, 86, 56): '"""\\\\`([^\\\\`]+)\\\\`"""', (86, 58, 86, 65): 'content'}, {}), "('\\\\`([^\\\\`]+)\\\\`', content)", False, 'import re\n'), ((116, 30, 116, 66), 're.findall', 're.findall', ({(116, 41, 116, 56): '"""\\\\`([^\\\\`]+)\\\\`"""', (116, 58, 116, 65): 'content'}, {}), "('\\\\`([^\\\\`]+)\\\\`', content)", False, 'import re\n'), ((146, 30, 146, 66), 're.findall', 're.findall', ({(146, 41, 146, 56): '"""\\\\`([^\\\\`]+)\\\\`"""', (146, 58, 146, 65): 'content'}, {}), "('\\\\`([^\\\\`]+)\\\\`', content)", False, 'import re\n'), ((176, 30, 176, 66), 're.findall', 're.findall', ({(176, 41, 176, 56): '"""\\\\`([^\\\\`]+)\\\\`"""', (176, 58, 176, 65): 'content'}, {}), "('\\\\`([^\\\\`]+)\\\\`', content)", False, 'import re\n')]