{
  lib,
  config,
  pkgs,
  ...
}: let
  cfg = config.hive.borg-server;
in {
  options.hive.borg-server = {
    enable = lib.mkEnableOption "Enable the borg server";
    package = lib.mkOption {
      type = lib.types.package;
      default = pkgs.borgbackup;
      example = "pkgs.borgbackup";
      description = "The borg package to use";
    };
    borg_user = lib.mkOption {
      type = lib.types.str;
      example = "borg";
      default = "borg";
      description = "The user for the borg repository home.";
    };
    repositories_path = lib.mkOption {
      type = lib.types.path;
      example = "/var/lib/borg-repositories";
      default = "/var/lib/borg-repositories";
      description = "The user for the borg repository home.";
    };
    repositories = lib.mkOption {
      type = lib.types.attrsOf (lib.types.submodule {
        options = {
          name = lib.mkOption {
            type = lib.types.nullOr (lib.types.strMatching "^[a-zA-Z0-9._-]+$");
            default = null;
            example = "borg-repo";
            description = "The name of the borg repository. If null, use key of attrset";
          };
          ssh_public_key = lib.mkOption {
            type = lib.types.singleLineStr;
            example = "ssh-rsa AAAA...";
            description = "The path to the public key for the borg repository.";
          };
        };
      });
    };
  };

  config = lib.mkIf cfg.enable {
    users.users.${cfg.borg_user} = {
      isNormalUser = true;
      description = "Borg user";
      home = cfg.repositories_path;
      createHome = true;
      extraGroups = ["borg"];
      openssh.authorizedKeys.keys =
        lib.attrsets.mapAttrsToList
        (key: repo: "command=\"${cfg.package}/bin/borg serve --restrict-to-path=${cfg.repositories_path}/${lib.defaultTo key repo.name}\",restrict ${repo.ssh_public_key}")
        cfg.repositories;
    };
  };
}
