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

let
  service = "zigbee2mqtt";
  cfg = config.homelab.${service};
  sec = config.sops.secrets;
  homelab = config.homelab;
in
{
  options.homelab.${service} = {
    enable = lib.mkEnableOption "enables ${service}";

    # set port options
    port = lib.mkOption {
      type = lib.types.int;
      default = 7705;
      description = "set port for ${service} (default: ${toString cfg.port}";
    };
    url = lib.mkOption {
      type = lib.types.str;
      default = "z2m.${homelab.base_domain}";
      description = "set domain for ${service}";
    };
    data_dir = lib.mkOption {
      type = lib.types.str;
      default = "/var/lib/${service}";
      description = "set data directory for ${service}";
    };
    ids = lib.mkOption {
      type = lib.types.int;
      default = cfg.port;
      description = "set uid and pid of ${service} user (matches port by default)";
    };
    backup = lib.mkOption {
      type = lib.types.bool;
      default = true;
      description = "enable backups for ${service}";
    };
    motd = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = service;
    };
  };

  config = lib.mkIf cfg.enable {
    
    # declare ${service} group
    users.groups.${service} = { gid = lib.mkForce cfg.ids; };

    # declare ${service} user
    users.users.${service} = {
      description = "${service} server user";
      uid = lib.mkForce cfg.ids;
      isSystemUser = true;
      home = cfg.data_dir;
      createHome = true;
      group = service;
      extraGroups = [];
    };

    # enable the ${service} service
    services.${service} = {
      enable = true;
      dataDir = cfg.data_dir;
      settings = {
          mqtt = {
            base_topic = "zigbee2mqtt";
            client_id = "zigbee2mqtt";
            server = "mqtt://localhost:1883";
            user = "!/run/secrets/mosquitto_passwd.yaml user";
            password = "!/run/secrets/mosquitto_passwd.yaml password";
            keepalive = 20;
          };
          serial = {
            port = "/dev/serial/by-id/usb-Itead_Sonoff_Zigbee_3.0_USB_Dongle_Plus_V2_4a4e75d63653ef1198d728e0174bec31-if00-port0";
            adapter = "ember";
          };
          advanced = {
            channel = 11;
          };
          frontend = {
            enabled = true;
            port = cfg.port;
          };
          homeassistant = {
            enabled = true;      
          };
      };
    };

    # override umask to make permissions work out
    systemd.services.${service}.serviceConfig = {
      UMask = lib.mkForce "0007";
      User = service;
      Group = service;
    };

#    # open firewall
    networking.firewall.allowedTCPPorts = [ cfg.port ];

    # add to caddy for reverse proxy
    services.caddy.virtualHosts."${cfg.url}" = {
      serverAliases = [ "z2m.${homelab.public_domain}" ];
      extraConfig = ''
        tls ${sec."ssl_blakedheld_crt".path} ${sec."ssl_blakedheld_key".path}
        reverse_proxy 127.0.0.1:${toString cfg.port}
      '';
    };

    # add to glance
    homelab.glance.links.services = [{
      title = service;
      url = "https://${cfg.url}";
      error-url = "http://${homelab.host_ip}:${toString cfg.port}";
      check-url = "http://${homelab.host_ip}:${toString cfg.port}";
      icon = "di:${service}"; }];

    sops.secrets = {
      "mosquitto_passwd.yaml" = {
        owner = service;
        group = service;
      };
    };

    # add to backups
    homelab.backups.baks = {
     ${service} = { paths = [ cfg.data_dir ]; };
    };
  };
}
