{
  config,
  pkgs,
  lib,
  ...
}: let
  service = "ensure_perms";
  cfg = config.holocron.${service};

  # define variables for paths
  archives_path = "/holocron/archives";
  media_path = "/holocron/media";
  users_path = "/holocron/users";
in {
  options.holocron.ensure_perms = {
    enable = lib.mkEnableOption "enables perms ensurence script";
  };

  config = lib.mkIf cfg.enable {
    # service to run periodically to reset the perms on all zpools
    # everything works fine without this, just for peace of mind
    # and to clean up the ownership from the arr stack in /holocron/media
    systemd.services.${service} = {
      description = "ensure file permissions for archives, media and user folders";
      serviceConfig = {
        Type = "oneshot";
        ExecStart = pkgs.writeShellScript "ensure_perms" ''

          # Fix ownership for archives directory
          echo "starting ${archives_path}"
          chown -Rc root:archives ${archives_path}
          find "${archives_path}" -type d -exec chmod 2770 "$@" {} +
          find "${archives_path}" -type f -exec chmod 660 "$@" {} +

          # Fix ownership for media directory
          echo "starting ${media_path}"
          chown -Rc root:media ${media_path}
          find "${media_path}" -type d -exec chmod 2770 "$@" {} +
          find "${media_path}" -type f -exec chmod 660 "$@" {} +

          # Fix user directories
          for user_dir in ${users_path}/*; do
            if [ -d "$user_dir" ]; then
              user=$(basename "$user_dir")
              echo "starting $user_dir"
              chown -Rc $user:$user $user_dir
              find $user_dir -type d -exec chmod 2770 "$@" {} +
              find $user_dir -type f -exec chmod 660 "$@" {} +
            fi
          done
          echo "fin"
        '';
      };
    };

    systemd.timers.${service} = {
      description = "run script to ensure_perms daily";
      wantedBy = ["timers.target"];
      timerConfig = {
        OnCalendar = "03:30";
        Persistent = true;
      };
    };
  };
}
