{
  pkgs,
  lib,
  nglib,
  config,
  ...
}: let
  cfg = config.services.atuin;
  cfgInit = config.init.services.atuin;
  settingsFormat = pkgs.formats.toml {};
in {
  options.services.atuin = {
    enable = lib.mkEnableOption "atuin";
    package = lib.mkPackageOption pkgs "atuin" {};

    settings = lib.mkOption {
      type = lib.types.submodule {
        freeformType = settingsFormat.type;

        options = {
          host = lib.mkOption {
            type = lib.types.str;
            default = "0.0.0.0";
            description = "The host to listen on";
          };

          port = lib.mkOption {
            type = lib.types.port;
            default = 8888;
            description = "The TCP port to listen on";
          };

          open_registration = lib.mkOption {
            type = lib.types.bool;
            default = false;
            description = "If true, accept new user registrations";
          };

          db_uri = lib.mkOption {
            type = with lib.types; nullOr str;
            default = null;
            description = "A valid PostgreSQL URI, for saving history";
          };

          path = lib.mkOption {
            type = lib.types.str;
            default = "";
            description = "A path to prepend to all the routes of the server";
          };
        };
      };
    };
  };

  config = lib.mkIf cfg.enable {
    init.services.atuin = {
      enabled = true;
      user = lib.mkDefault "atuin";
      group = lib.mkDefault "atuin";

      script = pkgs.writeShellScript "atuin-run" ''
        ${lib.getExe cfg.package} server start
      '';
    };

    environment = {
      systemPackages = [cfg.package];

      variables.ATUIN_CONFIG_DIR = let
        settingsFile = settingsFormat.generate "server.toml" (lib.filterAttrs (_: v: v != null) cfg.settings);
      in
        toString (pkgs.writeTextDir "server.toml" (builtins.readFile settingsFile));
    };

    users.users.${cfgInit.user} = nglib.mkDefaultRec {
      description = "atuin";
      inherit (cfgInit) group;
      createHome = false;
      home = "/var/empty";
      useDefaultShell = true;
      uid = config.ids.uids.atuin;
    };

    users.groups.${cfgInit.group} = nglib.mkDefaultRec {gid = config.ids.gids.atuin;};
  };
}