#!/usr/bin/env python3
"""Print an FWS installer text in the language of $LANG.

Usage: fws-i18n <key> [name=value ...]

Shell side of the installer translations: the live session (/root/.xinitrc)
shows dialogs after the installer has closed, in the language picked on its
first screen. Same file and same lookup as the installer screens, so a key is
translated once for both.
"""

import glob
import importlib.util
import sys


def main():
    if len(sys.argv) < 2:
        print(__doc__.strip().splitlines()[2], file=sys.stderr)
        return 2
    key = sys.argv[1]
    fields = dict(arg.split("=", 1) for arg in sys.argv[2:] if "=" in arg)
    text = key
    # The module sits in Anaconda's folder, whose path follows Python's version.
    for path in glob.glob("/usr/lib/python3*/site-packages/pyanaconda/ui/gui/spokes/fws_i18n.py"):
        try:
            spec = importlib.util.spec_from_file_location("fws_i18n", path)
            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)
            text = module.t(key, **fields)
        except Exception:  # pylint: disable=broad-except
            # A dialog with the key in it beats no dialog at all.
            pass
        break
    print(text)
    return 0


if __name__ == "__main__":
    sys.exit(main())
