Files
.hive/modules/services/calibre.nix
T

123 lines
3.6 KiB
Nix

{
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-users = "${cfg.basePath}/users.sqlite";
libraries = map (n: "${cfg.basePath}/${n}") cfg.libraries;
ensure-libs = lib.concatStrings (
map (l: ''
if [ ! -d "${l}" ]; then
echo "Creating Calibre libraray directory \"${l}\""
mkdir "${l}"
chown ${calibre-user}:${calibre-group} "${l}"
fi
if [ ! -f "${l}/metadata.db" ]; then
echo "Creating Calibre libraray metadata \"${l}\""
${calibre}/bin/calibredb --with-library="${l}" list
chown -R ${calibre-user}:${calibre-group} "${l}"
fi
'')
libraries
);
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";
};
libraries = lib.mkOption {
type = lib.types.listOf lib.types.singleLineStr;
example = ["library1" "private" "foo"];
default = ["library"];
description = "A list of libraries to serve. (Must be present in the base-path, will be initialized if not existing)";
};
};
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;
inherit libraries;
};
# Fallback server with only 403
services.nginx.virtualHosts.${config.networking.domain} = lib.mkDefault {
default = true;
locations."/".return = 403;
forceSSL = true;
enableACME = true;
};
# Virtual host for calibre
services.nginx.virtualHosts."${cfg.instanceFQDN}" = {
forceSSL = true;
enableACME = true;
locations."/" = {
proxyPass = "http://[::1]:${toString cfg.localPort}";
extraConfig = ''
client_max_body_size 150M;
'';
};
};
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
${ensure-libs}
'';
RemainAfterExit = true;
};
};
};
};
}