{
  config,
  lib,
  pkgs,
  namespace,
  ...
}:
with lib;
let
  name = "calibre";
  cfg = config.${namespace}.services.${name};

  calibreConfig = lib.${namespace}.mkModule {
    inherit config name;
    serviceName = "calibre-web";
    description = "Calibre Server";
    options = { };
    moduleConfig = {
      services = {
        calibre-server = {
          enable = false;
          openFirewall = true;
          port = cfg.port;
          libraries = [
            "${cfg.dataDir}/books"
          ];
        };
      };
    };
  };

  calibreWebConfig = lib.${namespace}.mkModule {
    inherit config;
    name = "${name}-web";
    description = "Calibre Web";
    options = { };
    moduleConfig = {
      services.calibre-web = {
        enable = true;
        openFirewall = true;
        package = pkgs.stable.calibre-web;
        dataDir = "${cfg.configDir}/calibre-web";
        listen = {
          ip = "0.0.0.0";
          port = cfg.port;
        };
        options = {
          enableBookUploading = true;
          enableBookConversion = true;
          calibreLibrary = "${cfg.dataDir}/books";
        };
      };
    };
  };
in
{
  imports = [
    calibreConfig
    calibreWebConfig
  ];
}
