Import('env')
Import('create_uninstall_target')
Import('VERSION')
Import('installing')

import os
import subprocess
from pathlib import Path

from SCons.Errors import BuildError


if env['HAVE_MSGFMT']:
    for src in env.Glob('*.po'):
        lang = os.path.basename(src.get_abspath())[:-3]
        mo = env.Command(f'{lang}.mo', src, 'msgfmt $SOURCE -o $TARGET')

        path = f'share/locale/{lang}/LC_MESSAGES/rmlint.mo'

        if installing:
            env.Alias(['install', 'install-cli'],
                      env.InstallAs('$staged_prefix/' + path, mo))

        if 'uninstall' in COMMAND_LINE_TARGETS:
            create_uninstall_target(env, '$PREFIX/' + path)


def xgettext_action(target, source, env):
    return subprocess.call(
        'xgettext --package-name rmlint -k_ -kN_ -kngettext:1,2 '
        f'--package-version {VERSION} '
        '--default-domain rmlint '
        '--add-location=file '
        f'{"--join-existing " if os.path.exists("po/rmlint.pot") else ""}'
        '--output po/rmlint.pot '
        '--from-code UTF-8 '
        '-w 100 '
        '$(find src lib -iname "*.[ch]") '
        '$(find gui/shredder -iname "*.py") '
        'gui/schemas/io.github.sahib.rmlint.Shredder.gschema.xml',
        shell=True
    )


def msgmerge_action(target, source, env):
    for p in Path('po').glob('*.po'):
        if subprocess.call((
            'msgmerge',
            '--update',
            '--backup=none',
            '-w', '100',
            str(p),
            'po/rmlint.pot',
        )):
            raise BuildError(f'msgmerge failed on {p}')


env.AlwaysBuild(env.Alias(
    'xgettext', None,
    env.Action(xgettext_action, "Extracting strings…")
))

env.AlwaysBuild(env.Alias(
    'msgmerge', None,
    env.Action(msgmerge_action, "Merging translations…")
))

env.AlwaysBuild(env.Alias('gettext', None, [
    env.Action(xgettext_action),
    env.Action(msgmerge_action)
]))
