{ config, lib, pkgs, ... }: lib.mkIf config.services.xmrig.enable { systemd.services.xmrig-auto-pause = { description = "Auto-pause xmrig when other services need CPU"; after = [ "xmrig.service" ]; wantedBy = [ "multi-user.target" ]; serviceConfig = { ExecStart = "${pkgs.python3}/bin/python3 ${./xmrig-auto-pause.py}"; Restart = "always"; RestartSec = "10s"; NoNewPrivileges = true; ProtectHome = true; ProtectSystem = "strict"; PrivateTmp = true; RestrictAddressFamilies = [ "AF_UNIX" # systemctl talks to systemd over D-Bus unix socket ]; MemoryDenyWriteExecute = true; StateDirectory = "xmrig-auto-pause"; }; environment = { POLL_INTERVAL = "3"; GRACE_PERIOD = "15"; # Background services (qbittorrent, bitmagnet, postgresql, etc.) produce # 15-25% non-nice CPU during normal operation. The stop threshold must # sit above transient spikes; the resume threshold must be below the # steady-state floor to avoid restarting xmrig while services are active. CPU_STOP_THRESHOLD = "40"; CPU_RESUME_THRESHOLD = "10"; STARTUP_COOLDOWN = "10"; STATE_DIR = "/var/lib/xmrig-auto-pause"; }; }; }