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

with lib;

let
  cfg = config.services.clerie-gc-dir;

  gcdirServices = mapAttrs' (name: options:
    nameValuePair "clerie-gc-dir-${name}" {
      serviceConfig = {
        Type = "oneshot";
        User = options.user;
        #Group = if (options.group) != null then options.group else config.users.user.${options.user}.group;
      };

      script = ''
        find ${options.dir} -depth -mindepth 1 -mtime +20 -delete
      '';
    }
  ) cfg.dirs;

  gcdirTimers = mapAttrs' (name: options:
    nameValuePair "clerie-gc-dir-${name}" {
      wantedBy = [ "timers.target" ];
      timerConfig = {
        OnCalendar = "hourly";
        RandomizedDelaySec = "1h";
      };
    }
  ) cfg.dirs;

  dirOptions = { ... }: {
    options = {
      user = mkOption {
        type = types.str;
      };
      group = mkOption {
        type = with types; nullOr str;
        default = null;
      };
      dir = mkOption {
        type = types.str;
      };
    };
  };
in {
  options = {
    services.clerie-gc-dir = {
      enable = mkEnableOption "clerie's Directory Garbage Collector";
      dirs = mkOption {
        type = with types; attrsOf (submodule dirOptions);
        default = {};
      };
    };
  };

  config = mkIf cfg.enable {
    systemd.services = gcdirServices;
    systemd.timers = gcdirTimers;
  };
}