{ options, config, pkgs, lib, ... }: with lib; let cfg = config.services.sdm2mqtt; settingsFormat = pkgs.formats.json {}; configFile = settingsFormat.generate "sdm2mqtt-config.json" cfg.config; in { options = { services.sdm2mqtt = with lib; { enable = mkEnableOption "sdm2mqtt - Exporter for SDM120M meters to mqtt, written in nim"; package = mkOption { type = types.package; default = pkgs.sdm2mqtt; }; config = mkOption { type = settingsFormat.type; default = {}; example = {}; }; environmentFiles = mkOption { type = types.listOf types.path; default = []; example = [ "/run/keys/sdm2mqtt.env" ]; description = lib.mdDoc '' File to load as environment file. Environment variables from this file will be interpolated into the config file using envsubst. This is useful to avoid putting secrets into the nix store. ''; }; }; }; config = lib.mkIf cfg.enable { systemd.services.sdm2mqtt = { after = [ "network-online.target" ]; wantedBy = [ "multi-user.target" ]; environment.CONFIG_PATH = ( if cfg.environmentFiles == [] then configFile else "/var/run/sdm2mqtt/config.json" ); serviceConfig = { DynamicUser = true; Restart = "on-failure"; RestartSec = 5; RuntimeDirectory = "sdm2mqtt"; EnvironmentFile = cfg.environmentFiles; ExecStart = "${cfg.package}/bin/sdm2mqtt"; ExecStartPre = lib.optional (cfg.environmentFiles != []) (pkgs.writeShellScript "sdm2mqtt-preStart" '' umask 077 ${pkgs.envsubst}/bin/envsubst -i "${configFile}" > /var/run/sdm2mqtt/config.json ''); NoNewPrivileges = true; PrivateTmp = true; ProtectSystem = "strict"; ProtectKernelLogs = true; ProtectKernelModules = true; ProtectKernelTunables = true; ProtectControlGroups = true; ProtectHome = true; RestrictAddressFamilies = lib.mkDefault "AF_UNIX AF_INET AF_INET6"; RestrictNamespaces = true; RestrictRealtime = true; DevicePolicy = "closed"; LockPersonality = true; LimitNPROC = 1; }; }; }; }