{ config, pkgs, ... }:

let
  latestRenovate = pkgs.unstable.renovate.overrideAttrs (finalAttrs: prevAttrs: {
    version = "39.138.0";

    src = pkgs.fetchFromGitHub {
      owner = "renovatebot";
      repo = "renovate";
      tag = finalAttrs.version;
      hash = "sha256-kSN5rrVWBhko0MNLbaD/hHl7nJsLErfKsgxNT1/X79A=";
    };
    pnpmDeps = pkgs.pnpm_9.fetchDeps {
      inherit (finalAttrs) pname version src;
      hash = "sha256-yOKQjbU7PMUaBFBNsYQMSj1kT/f4FezdcNvjgeeXNNg=";
    };
  });
in
{
  age.secrets.renovate-gitea-token.file = ./renovate-gitea-token.age;
  age.secrets.renovate-github-token.file = ./renovate-github-token.age;

  systemd.services.renovate-clear-cache = {
    script = ''
      set -eu
      ${pkgs.coreutils}/bin/rm -rf /var/cache/private/renovate /var/lib/renovate
    '';
    serviceConfig = {
      Type = "oneshot";
      User = "root";
    };
    startAt = "3:00";
  };

  services.renovate = {
    enable = true;
    package = latestRenovate;
    schedule = "0..2,10..23:00";
    credentials = {
      RENOVATE_TOKEN = config.age.secrets.renovate-gitea-token.path;
      GITHUB_COM_TOKEN = config.age.secrets.renovate-github-token.path;
    };
    runtimePackages = with pkgs.unstable; [
      pnpm
      python312
      poetry
      gnumake
      cargo
    ];
    settings = {
      platform = "gitea";
      endpoint = "https://git.pleshevski.ru";
      assignees = [ "pleshevskiy" ];
      autodiscover = true;
      packageRules = [
        {
          matchUpdateTypes = [ "minor" "patch" "pin" "digest" ];
          automerge = true;
        }
      ];
      automergeStrategy = "fast-forward";
      onboardingConfig = {
        "$schema" = "https://docs.renovatebot.com/renovate-schema.json";
        extends = [ "config:recommended" ];
        configMigration = true;
      };
      globalExtends = [ "npm:unpublishSafe" ];

      cacheHardTtlMinutes = 30;
      httpCacheTtlDays = 1;
    };
  };

  # systemd.services.renovate.environment.LOG_LEVEL = "debug";
}