#!/usr/bin/python3
"""
Set image's default keymap

Sets the default console keyboard layout to `keymap`, like 'us' or 'de-latin1'.

Removes any existing /etc/vconsole.conf, then runs `systemd-firstboot` with the
`--keymap` option, which sets KEYMAP in /etc/vconsole.conf.

Valid keymaps are generally found in /lib/kbd/keymaps.
"""


import subprocess
import sys
import os

import osbuild.api


SCHEMA = """
"additionalProperties": false,
"required": ["keymap"],
"properties": {
  "keymap": {
    "type": "string",
    "description": "Name of keymap to use"
  }
}
"""

def main(tree, options):
    keymap = options["keymap"]

    # We need to remove the /etc/vconsole.conf file first, because it is created while we install RPM packages.
    # systemd-firstboot expects that if /etc/vconsole.conf exists it is a user-defined value and does not change it, but
    # the assumption is wrong, because it contains a default value from RPM package.
    try:
        os.remove(f"{tree}/etc/vconsole.conf")
        print("/etc/vconsole.conf already exists. Replacing.")
    except FileNotFoundError:
        pass

    subprocess.run(["systemd-firstboot", f"--root={tree}", f"--keymap={keymap}"], check=True)

    return 0


if __name__ == '__main__':
    args = osbuild.api.arguments()
    r = main(args["tree"], args["options"])
    sys.exit(r)
