{
  config,
  lib,
  pkgs,
  utils,
  ...
}:
let
  cfg = config.services.kanata;

  upstreamDoc = "See [the upstream documentation](https://github.com/jtroo/kanata/blob/main/docs/config.adoc) and [example config files](https://github.com/jtroo/kanata/tree/main/cfg_samples) for more information.";

  keyboard =
    { name, config, ... }:
    {
      options = {
        devices = lib.mkOption {
          type = lib.types.listOf lib.types.str;
          default = [ ];
          example = [ "/dev/input/by-id/usb-0000_0000-event-kbd" ];
          description = ''
            Paths to keyboard devices.

            An empty list, the default value, lets kanata detect which
            input devices are keyboards and intercept them all.
          '';
        };
        config = lib.mkOption {
          type = lib.types.lines;
          example = ''
            (defsrc
              caps)

            (deflayermap (default-layer)
              ;; tap caps lock as caps lock, hold caps lock as left control
              caps (tap-hold 100 100 caps lctl))
          '';
          description = ''
            Configuration other than `defcfg`.

            ${upstreamDoc}
          '';
        };
        extraDefCfg = lib.mkOption {
          type = lib.types.lines;
          default = "";
          example = "danger-enable-cmd yes";
          description = ''
            Configuration of `defcfg` other than `linux-dev` (generated
            from the devices option) and
            `linux-continue-if-no-devs-found` (hardcoded to be yes).

            ${upstreamDoc}
          '';
        };
        configFile = lib.mkOption {
          type = lib.types.path;
          default = mkConfig name config;
          defaultText = "A config file generated by values from other kanata module options.";
          description = ''
            The config file.

            By default, it is generated by values from other kanata
            module options.

            You can also set it to your own full config file which
            overrides all other kanata module options.  ${upstreamDoc}
          '';
        };
        extraArgs = lib.mkOption {
          type = lib.types.listOf lib.types.str;
          default = [ ];
          description = "Extra command line arguments passed to kanata.";
        };
        port = lib.mkOption {
          type = lib.types.nullOr lib.types.port;
          default = null;
          example = 6666;
          description = ''
            Port to run the TCP server on. `null` will not run the server.
          '';
        };
      };
    };

  mkName = name: "kanata-${name}";

  mkDevices =
    devices:
    let
      devicesString = lib.pipe devices [
        (map (device: "\"" + device + "\""))
        (lib.concatStringsSep " ")
      ];
    in
    lib.optionalString ((lib.length devices) > 0) "linux-dev (${devicesString})";

  mkConfig =
    name: keyboard:
    pkgs.writeTextFile {
      name = "${mkName name}-config.kdb";
      text = ''
        (defcfg
          ${keyboard.extraDefCfg}
          ${mkDevices keyboard.devices}
          linux-continue-if-no-devs-found yes)

        ${keyboard.config}
      '';
      # Only the config file generated by this module is checked.  A
      # user-provided one is not checked because it may not be available
      # at build time.  I think this is a good balance between module
      # complexity and functionality.
      checkPhase = ''
        ${lib.getExe cfg.package} --cfg "$target" --check --debug
      '';
    };

  mkService =
    name: keyboard:
    lib.nameValuePair (mkName name) {
      wantedBy = [ "multi-user.target" ];
      serviceConfig = {
        Type = "notify";
        ExecStart = ''
          ${lib.getExe cfg.package} \
            --cfg ${keyboard.configFile} \
            --symlink-path ''${RUNTIME_DIRECTORY}/${name} \
            ${lib.optionalString (keyboard.port != null) "--port ${toString keyboard.port}"} \
            ${utils.escapeSystemdExecArgs keyboard.extraArgs}
        '';

        DynamicUser = true;
        RuntimeDirectory = mkName name;
        SupplementaryGroups = with config.users.groups; [
          input.name
          uinput.name
        ];

        # hardening
        DeviceAllow = [
          "/dev/uinput rw"
          "char-input r"
        ];
        CapabilityBoundingSet = [ "" ];
        DevicePolicy = "closed";
        IPAddressAllow = lib.optional (keyboard.port != null) "localhost";
        IPAddressDeny = [ "any" ];
        LockPersonality = true;
        MemoryDenyWriteExecute = true;
        PrivateNetwork = keyboard.port == null;
        PrivateUsers = true;
        ProcSubset = "pid";
        ProtectClock = true;
        ProtectControlGroups = true;
        ProtectHome = true;
        ProtectHostname = true;
        ProtectKernelLogs = true;
        ProtectKernelModules = true;
        ProtectKernelTunables = true;
        ProtectProc = "invisible";
        RestrictAddressFamilies = [ "AF_UNIX" ] ++ lib.optional (keyboard.port != null) "AF_INET";
        RestrictNamespaces = true;
        RestrictRealtime = true;
        SystemCallArchitectures = [ "native" ];
        SystemCallFilter = [
          "@system-service"
          "~@privileged"
          "~@resources"
        ];
        UMask = "0077";
      };
    };
in
{
  options.services.kanata = {
    enable = lib.mkEnableOption "kanata, a tool to improve keyboard comfort and usability with advanced customization";
    package = lib.mkPackageOption pkgs "kanata" {
      example = [ "kanata-with-cmd" ];
      extraDescription = ''
        ::: {.note}
        If {option}`danger-enable-cmd` is enabled in any of the keyboards, the
        `kanata-with-cmd` package should be used.
        :::
      '';
    };
    keyboards = lib.mkOption {
      type = lib.types.attrsOf (lib.types.submodule keyboard);
      default = { };
      description = "Keyboard configurations.";
    };
  };

  config = lib.mkIf cfg.enable {
    warnings =
      let
        keyboardsWithEmptyDevices = lib.filterAttrs (name: keyboard: keyboard.devices == [ ]) cfg.keyboards;
        existEmptyDevices = lib.length (lib.attrNames keyboardsWithEmptyDevices) > 0;
        moreThanOneKeyboard = lib.length (lib.attrNames cfg.keyboards) > 1;
      in
      lib.optional (existEmptyDevices && moreThanOneKeyboard)
        "One device can only be intercepted by one kanata instance.  Setting services.kanata.keyboards.${lib.head (lib.attrNames keyboardsWithEmptyDevices)}.devices = [ ] and using more than one services.kanata.keyboards may cause a race condition.";

    hardware.uinput.enable = true;

    systemd.services = lib.mapAttrs' mkService cfg.keyboards;
  };

  meta.maintainers = with lib.maintainers; [ linj ];
}
