{pkgs, ...}: 
let 
  globals = import ../../config/globals.nix ;
in {
  environment.systemPackages = with pkgs; [
    goaccess
  ];

  environment.etc."local/bin/generate-goaccess.sh".text = ''
    #!/bin/sh 
    set -eu

    RAW_LOG="/var/log/caddy/access-${globals.services.levr.url}.log"
    CLEAN_LOG="/tmp/goaccess-clean.log"
    REPORT="${globals.services.goaccess.home}/index.html"

    ${pkgs.gnugrep}/bin/grep -v '192.168.' "$RAW_LOG" > "$CLEAN_LOG"
    ${pkgs.goaccess}/bin/goaccess "$CLEAN_LOG" --log-format=CADDY -o "$REPORT";
  '';
  environment.etc."local/bin/generate-goaccess.sh".mode = "0755";

  systemd.services.goaccess-report = {
    description = "Generate GoAccess HTML report";
    serviceConfig = {
      ExecStart = "/etc/local/bin/generate-goaccess.sh";
    };
  };

  # Timer pour régénérer le rapport toutes les heures
  systemd.timers.goaccess-report = {
    description = "Hourly GoAccess report generation";
    wantedBy = ["timers.target"];
    timerConfig = {
      OnCalendar = "hourly";
      Persistent = true;
    };
  };
  services.caddy = {
    virtualHosts = {
      "${globals.services.goaccess.url}" = {
        extraConfig = ''
          root * ${globals.services.goaccess.home}
          file_server browse
          try_files {path} {path}/ /index.html

        '';
      };
    };
  };

  systemd.tmpfiles.rules = [
    "d ${globals.services.goaccess.home} 0755 root root -"
  ];
}
