{
  config,
  lib,
  namespace,
  ...
}:
with lib;
let
  inherit (lib.${namespace}) mkOpt;
  cfg = config.${namespace}.power.ups;
in
{
  options.${namespace}.power.ups = {
    enable = mkEnableOption "Enable UPS support";

    upsName = mkOpt types.str "nas-ups" "Name of the ups";
    upsUser = mkOpt types.str "nas-admin" "Name of the ups user";

    upsdPort = mkOpt types.int 3493 "Port for upsd";
  };

  config = mkIf cfg.enable {
    power.ups = {
      enable = true;
      openFirewall = true;
      mode = "netserver";

      ups = {
        "${cfg.upsName}" = {
          description = "NAS UPS";
          driver = "usbhid-ups";
          port = "auto";
        };
      };

      users."${cfg.upsUser}" = {
        passwordFile = config.sops.secrets."jallen-nas/ups_password".path;
        actions = [ "ALL" ];
        instcmds = [ "ALL" ];
        upsmon = "primary";
      };

      upsmon = {
        enable = true;
        monitor."${cfg.upsName}" = {
          passwordFile = config.sops.secrets."jallen-nas/ups_password".path;
          user = cfg.upsUser;
        };
      };

      upsd = {
        enable = false;
        listen = [
          {
            address = "0.0.0.0";
            port = 3493;
          }
        ];
      };
    };

    services = {
      apcupsd = {
        enable = true;
      };
    };
  };
}
