{ flake.nixosModules.calibre = { config, lib, pkgs, ... }: let cfg = config.hive.calibre; calibre = config.services.calibre-server.package; calibre-user = config.services.calibre-server.user; calibre-group = config.services.calibre-server.group; calibre-library = "${cfg.basePath}/library"; calibre-users = "${cfg.basePath}/users.sqlite"; in { options.hive.calibre = { enable = lib.mkEnableOption "Enable calibre server"; localPort = lib.mkOption { type = lib.types.int; example = 8080; default = 45988; description = "Specify the local port calibre server uses."; }; basePath = lib.mkOption { type = lib.types.path; example = "/var/calibre-server"; default = "/srv/calibre-server"; description = "The base-path for calibre data"; }; instanceFQDN = lib.mkOption { type = lib.types.singleLineStr; example = "calibre.example.com"; description = "Fully qualified domain name of the calibre instance"; }; }; config = lib.mkIf cfg.enable { services.calibre-server = { enable = true; auth.enable = true; auth.mode = "auto"; auth.userDb = "${calibre-users}"; host = "::1"; port = cfg.localPort; libraries = [ "${calibre-library}" ]; }; # Virtual host for calibre services.nginx.virtualHosts."${cfg.instanceFQDN}" = { forceSSL = true; enableACME = true; locations."/" = { proxyPass = "http://[::1]:${toString cfg.localPort}"; }; }; environment.systemPackages = [ (pkgs.writeShellScriptBin "calibre-manager-users" '' sudo -u ${calibre-user} ${calibre}/bin/calibre-server --userdb=${calibre-users} --manage-users '') ]; systemd.services.calibre-init = { description = "Initialize Calibre databases"; wantedBy = ["calibre-server.service"]; before = ["calibre-server.service"]; serviceConfig = { Type = "oneshot"; ExecStart = pkgs.writeShellScript "calibre-init" '' if [ ! -d ${cfg.basePath} ]; then echo "Creating Calibre base directory \"${cfg.basePath}\"" mkdir ${cfg.basePath} chown ${calibre-user}:${calibre-group} ${cfg.basePath} fi if [ ! -d ${calibre-library} ]; then echo "Creating Calibre libraray directory \"${calibre-library}\"" mkdir ${calibre-library} chown ${calibre-user}:${calibre-group} ${calibre-library} fi if [ ! -f ${calibre-library}/metadata.db ]; then echo "Creating Calibre libraray metadata \"${calibre-library}\"" ${calibre}/bin/calibredb --with-library=${calibre-library} list chown -R ${calibre-user}:${calibre-group} ${calibre-library} fi ''; RemainAfterExit = true; }; }; }; }; }