{
  lib,
  config,
  options,
  ...
}:
let
  inherit (lib) mkIf mkOption mkEnableOption;
  inherit (lib.types)
    enum
    listOf
    submodule
    nonEmptyStr
    str
    ;
  cfg = config.modules.server.navidrome;
in
{
  options.modules.server.navidrome = {
    enable = mkEnableOption "Navidrome";

    library = {
      type = mkOption {
        type = enum [
          "local"
          "nfs"
        ];
        default = "local";
      };
      path = mkOption { type = nonEmptyStr; };
      source = mkOption {
        default = { };
        type = submodule {
          options = {
            ip = mkOption { type = nonEmptyStr; };
            path = mkOption { type = nonEmptyStr; };
            options = mkOption {
              default = [
                "x-systemd.automount"
                "ro"
              ];
              type = listOf nonEmptyStr;
            };
          };
        };
      };
    };
    settings = options.services.navidrome.settings;
    restartPolicy = mkOption {
      type = str;
      default = "always";
      defaultText = ''
        Refer to https://www.mankier.com/5/systemd.service#Options-Restart for possible values,
        defines the restart behaviour in case the program ends.
      '';
    };
  };

  config = mkIf cfg.enable {
    fileSystems.${cfg.library.path} = mkIf (cfg.library.type == "nfs") {
      device = "${cfg.library.source.ip}:${cfg.library.source.path}";
      fsType = "nfs";
      options = cfg.library.source.options;
    };

    systemd.tmpfiles.rules = mkIf (cfg.library.type == "nfs") [
      "d ${cfg.library.path} - ${config.services.navidrome.group} - -"
    ];

    services.navidrome = {
      enable = true;
      openFirewall = true;
      settings = {
        MusicFolder = cfg.library.path;
      } // cfg.settings;
    };

    systemd.services.navidrome = {
      serviceConfig = {
        Restart = cfg.restartPolicy;
        EnvironmentFile = config.age.secrets.navidrome.path;
      };
      unitConfig = {
        RequiresMountsFor = mkIf (cfg.library.type == "nfs") [ cfg.library.path ];
      };
    };
  };
}
