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

let
  cfg = config.services.ha-mqtt-agent;
in
{
  options.services.ha-mqtt-agent = {
    enable = lib.mkEnableOption "enable ha-mqtt-agent";

    buttons.enable = lib.mkEnableOption "enable buttons" // { default = true; };

    dbm = {
      enable = lib.mkEnableOption "enable display brightness manager";
      displayDevice = lib.mkOption { type = lib.types.str; };
      touchDevice = lib.mkOption { type = lib.types.str; };
    };

    device = {
      id = lib.mkOption { type = lib.types.str; };
      name = lib.mkOption { type = lib.types.str; };
    };

    mqtt = {
      hostname = lib.mkOption { type = lib.types.str; };
      username = lib.mkOption { type = lib.types.str; };
      passwordFile = lib.mkOption { type = lib.types.str; };
    };

    user = lib.mkOption {
      default = "ha-mqtt-agent";
      type = lib.types.str;
    };
    group = lib.mkOption {
      default = "ha-mqtt-agent";
      type = lib.types.str;
    };
  };

  config = lib.mkIf cfg.enable {
    users.users."${cfg.user}" = {
      isSystemUser = true;
      group = cfg.group;
      extraGroups = []
        ++ (lib.optionals cfg.dbm.enable [ "input" "video" ]);
    };

    users.groups."${cfg.group}" = {};

    security.sudo = lib.mkIf cfg.buttons.enable {
      enable = true;
      extraRules = [{
        commands = [
          {
            command = "${pkgs.systemd}/bin/systemctl reboot";
            options = [ "NOPASSWD" ];
          }
          {
            command = "${pkgs.systemd}/bin/systemctl poweroff";
            options = [ "NOPASSWD" ];
          }
        ];
        users = [ cfg.user ];
      }];
    };

    systemd.services."ha-mqtt-agent" = let
      scriptStart = ''
        export MQTT_PASS=$(cat "''${MQTT_PASS_FILE}")

        ${pkgs.ha-mqtt-agent}/bin/ha-mqtt-agent \
          --device-id "${cfg.device.id}" \
          --device-name "${cfg.device.name}" \
          --mqtt-host "${cfg.mqtt.hostname}" \
          --mqtt-user "${cfg.mqtt.username}"'';

      scriptTail = if cfg.dbm.enable then '' \
          --display-device "${cfg.dbm.displayDevice}" \
          --touch-device "${cfg.dbm.touchDevice}"
        '' else "";

      script = (scriptStart + scriptTail);
    in {
      inherit script;

      wantedBy = [ "multi-user.target" ];
      after = [ "network-online.target" ];
      wants = [ "network-online.target" ];
      path = [ pkgs.bash "/run/wrappers" ];
      environment = {
        MQTT_PASS_FILE = "%d/mqtt_pass";
      };
      serviceConfig = {
        LoadCredential = "mqtt_pass:${cfg.mqtt.passwordFile}";
        Restart = "on-failure";
        RestartSec = 3;
        User = cfg.user;
      };
    };
  };
}