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

{
  options.c3d2.pi-sensors = lib.mkOption {
    default = [];
    type = with lib.types; listOf (submodule (_: {
      options = {
        type = lib.mkOption {
          description = "Sensor type";
          type = enum ["dht22"];
        };
        pin = lib.mkOption {
          description = "GPIO pin";
          type = int;
        };
        location = lib.mkOption {
          description = "Sensor location";
          type = str;
        };
      };
    }));
  };

  config = lib.mkIf (config.c3d2.pi-sensors != []) {
    # GPIO requires access to /dev/mem
    security.wrappers.pi-sensors = {
      setuid = true;
      owner = "root";
      group = "root";
      source = "${pkgs.pi-sensors}/bin/pi-sensors";
    };

    services.collectd.plugins.exec = ''
      Exec "${config.services.collectd.user}" "/run/wrappers/bin/pi-sensors" "2"${lib.concatMapStrings (s: " \"${s}\"") (
        lib.concatMap ({ type, pin, location }:
          [ type (toString pin) location ]
        ) config.c3d2.pi-sensors
      )}
    '';
  };
}
