{ lib, config, pkgs, utils, ... }:

with lib;

let
  cfg = config.services.prometheus.exporters.lvm;
in {
  options = {
    services.prometheus.exporters.lvm = {
      enable = mkEnableOption "Prometheus LVM exporter";

      listenAddress = mkOption {
        type = types.nullOr types.str;
        default = "127.0.0.1";
      };
      port = mkOption {
        type = types.port;
        default = 9845;
      };

      openFirewall = mkOption {
        type = types.bool;
        default = false;
        description = ''
          Open port in firewall for incoming connections.
        '';
      };
      firewallFilter = mkOption {
        type = types.nullOr types.str;
        default = null;
        example = literalExpression ''
          "-i eth0 -p tcp -m tcp --dport ${toString cfg.port}"
        '';
        description = ''
          Specify a filter for iptables to use when
          {option}`services.prometheus.exporters.lvm.openFirewall`
          is true. It is used as `ip46tables -I nixos-fw firewallFilter -j nixos-fw-accept`.
        '';
      };
    };
  };

  config = mkIf cfg.enable {
    systemd.services."prometheus-lvm-exporter" = {
      wantedBy = [ "multi-user.target" ];
      after = [ "network.target" ];

      serviceConfig = {
        ExecStart = "${pkgs.prometheus-lvm-exporter}/bin/prometheus-lvm-exporter ${utils.escapeSystemdExecArgs [
          "--web.systemd-socket"
        ]}";

        Restart = "always";
        Sockets = "prometheus-lvm-exporter.socket";
      };
    };

    systemd.sockets."prometheus-lvm-exporter" = {
      socketConfig.ListenStream = "${optionalString (cfg.listenAddress != null) (cfg.listenAddress + ":")}${toString cfg.port}";
    };
  };
}