{ pkgs, lib, config, ... }:
let
  cfg = config.mods.server.cal;
  port = config.mods.server.nginx.ports.cal;
in with lib; {
  options.mods.server = {
    cal = {
      enable = mkEnableOption {
        default = false;
        description = "enables radicale server";
      };
    };
  };

  config = mkIf cfg.enable {
    services.radicale = {
      enable = true;
      settings = {
        server = { hosts = [ "0.0.0.0:${toString port}" ]; };
        auth = {
          type = "htpasswd";
          htpasswd_filename = "${toString config.sops.secrets.htpasswd.path}";
          htpasswd_encryption = "bcrypt";
        };
        storage = { filesystem_folder = "/var/lib/radicale/collections"; };
      };
      rights = {
        root = {
          user = ".+";
          collection = "";
          permissions = "R";
        };
        principal = {
          user = ".+";
          collection = "{user}";
          permissions = "RW";
        };
        calendars = {
          user = ".+";
          collection = "{user}/[^/]+";
          permissions = "rw";
        };
      };
    };
  };
}
