#!/usr/bin/python3

# SPDX-FileCopyrightText: 2021-2024 Pino Toscano <pino@debian.org>
# SPDX-License-Identifier: GPL-2.0-or-later

import pathlib
import shutil
import sys

# known language mappings for MySQL/MariaDB language files;
# "english" is not present here, as it is handled on its own
language_mappings = {
    "bulgarian": "bg",
    "chinese": "zh_CN",
    "czech": "cs",
    "danish": "da",
    "dutch": "nl",
    "estonian": "et",
    "french": "fr",
    "georgian": "ka",
    "german": "de",
    "greek": "el",
    "hindi": "hi",
    "hungarian": "hu",
    "italian": "it",
    "japanese": "ja",
    "korean": "ko",
    "norwegian": "nb",
    "norwegian-ny": "nn",
    "polish": "pl",
    "portuguese": "pt",
    "romanian": "ro",
    "russian": "ru",
    "serbian": "sr",
    "slovak": "sk",
    "spanish": "es",
    "swedish": "sv",
    "ukrainian": "uk",
}


def fail(msg):
    print(f"ERROR: {msg}", file=sys.stderr)
    sys.exit(1)


def do_copy(srcfile, destdir):
    destfile = destdir / "errmsg.sys"
    destdir.mkdir(parents=True, exist_ok=True)
    print(f"Copying {srcfile} -> {destfile}")
    shutil.copy2(srcfile, destfile)


if len(sys.argv) != 3:
    fail(f"syntax: {sys.argv[0]} SOURCE_DIR DESTINATION_DIR")

source_dir = pathlib.Path(sys.argv[1])
destination_dir = pathlib.Path(sys.argv[2])

errmsg_files = source_dir.glob("*/errmsg.sys")
english_errmsg = None
language_files = []
unhandled_files = []
for errmsg_file in errmsg_files:
    language = errmsg_file.parent.name
    if language == "english":
        english_errmsg = errmsg_file
        continue
    try:
        language_files.append((errmsg_file, language_mappings[language]))
    except KeyError:
        unhandled_files.append(errmsg_file)

if not english_errmsg:
    fail("missing english errmsg.sys")

for uf in sorted(unhandled_files):
    print(f"WARNING: unhandled localized file: {uf}", file=sys.stderr)

do_copy(english_errmsg, destination_dir)
for errmsg_file, language in sorted(language_files):
    destdir = destination_dir / "l10n" / language
    do_copy(errmsg_file, destdir)
