#!/usr/bin/python3

import polib
import re
import sys

def main (f, d=None):
    po = polib.pofile(f, wrapwidth=0)
    option_re = re.compile(r'-[-a-z0-9[\]]+')
    linkgit_re = re.compile(r'((linkgit:)?(git[-a-z0-9[\]]+|mail)(\[[157]\]|\([157]\))(,|;)?(\n| )?)+')
    quoted_re = re.compile(r'`[a-zA-Z-_]+`|\'(oneline|short|medium|full(er)?|email|raw)\'|(user|transfer|submodule|stash|status|splitIndex|showbranch|sendemail|repack|remote|receive|push|merge(tool)?|mailinfo|log|interactive|instaweb|i18n|help|gui|gitweb|fastimport|format|fetch|diff(tool)?|credential|commit|column|core|branch|apply|color|git-p4)\.[a-zA-Z_.]+|araxis|bc3?|codecompare|deltawalker|guiffy|meld|diff(use|merge)|(exam|g?vim|t?k|open|xx)?diff[23]?|(ec?|p4|s|tortoise|win)merge|update|create|delete|verify|option|resolve|recursive|octopus|ours|subtree|theirs|patience|diff-algorithm=\[[a-z\|]+\]|ignore-(space-change|all-space|(cr|space)-at-eol)|(no-)?renormalize|no-renames')
    env_var_re = re.compile(r'`?GIT_[A-Z_\d]+`?')
    if not d is None:
            po_file=polib.pofile(d)
            pod = [(re.compile(entry.msgid), entry.msgstr) for entry in po_file]
    for entry in po:
        if option_re.fullmatch(entry.msgid) \
           or linkgit_re.fullmatch(entry.msgid) \
           or quoted_re.fullmatch(entry.msgid) \
           or env_var_re.fullmatch(entry.msgid):
            entry.msgstr = entry.msgid
            entry.flags.append("ignore-same")
            flags = sorted(set(entry.flags))
            entry.flags = list(flags)
            remove_fuzzy(entry)
        elif not d is None:
            for (entryre, entryrep) in pod:
                if entryre.fullmatch(entry.msgid):
                    entry.msgstr = entryre.sub(entryrep, entry.msgid)
                    remove_fuzzy(entry)
                    break
        if "..." in entry.msgid:
            entry.flags = list(sorted(set(entry.flags + ["ignore-ellipsis"])))
    po.save(f)

def remove_fuzzy (entry):
            if 'fuzzy' in entry.flags:
                entry.flags.remove('fuzzy')
                entry.previous_msgid = None


if __name__ == '__main__':
    if len(sys.argv)>2:
        main(sys.argv[1], sys.argv[2])
    elif len(sys.argv)>1:
        main(sys.argv[1])