{ config, lib, pkgs, ... }: let cfg = config.services.vnstati; in { options.services.vnstati = with lib; { enable = mkEnableOption "just some fancy traffic pics"; title = mkOption { type = types.str; default = "${if config.networking ? domain then config.networking.hostName else config.networking.fqdn}"; }; domain = mkOption { type = types.str; default = "${config.networking.fqdn}"; }; subdirectory = mkOption { type = types.str; default = "/traffic/"; }; }; config = lib.mkIf cfg.enable { assertions = [ ({ assertion = config.services.vnstat.enable; message = "vnstati requires vnstat.enable == true"; }) ]; fileSystems."/var/lib/vnstati" = { device = "tmpfs"; fsType = "tmpfs"; options = [ "rw" "size=30M" ]; }; services.nginx.virtualHosts.${cfg.domain} = { locations.${cfg.subdirectory} = { alias = "/var/lib/vnstati/"; index = "index.html"; }; }; systemd.services.vnstati = { wantedBy = [ "multi-user.target" ]; after = [ "var-lib-vnstati.mount" "vnstat.service" ]; startAt = "*-*-* *:0/10:00"; path = with pkgs; [ vnstat jq nix ]; serviceConfig = { User = "vnstatd"; Group = "vnstatd"; StateDirectory = "vnstati"; PrivateTmp = true; ProtectHome = true; ProtectSystem = "strict"; }; script = '' set -x ifaces=$(vnstat --json | jq -r .interfaces[].name | grep -v "^lo$") echo $ifaces nix eval -I nixpkgs=${lib.cleanSource pkgs.path} --raw -f ${./vnstati-html.nix} html \ --argstr ifaces "$ifaces" \ --argstr hostname "${cfg.title}" \ > /var/lib/vnstati/index.html for iface in $ifaces do vnstati -s -nh -i $iface -o /var/lib/vnstati/$iface-summary.png vnstati -h -nh -i $iface -o /var/lib/vnstati/$iface-hourly.png vnstati -d -nh -i $iface -o /var/lib/vnstati/$iface-daily.png vnstati -m -nh -i $iface -o /var/lib/vnstati/$iface-monthly.png vnstati -t -nh -i $iface -o /var/lib/vnstati/$iface-top10.png done ''; }; }; }