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

with lib;

let
  sshConfig = ''
    Include /etc/ssh/ssh_config

    ControlMaster auto
    ControlPath /var/lib/borg/.borgssh-master-%r@%n:%p
    ControlPersist yes

    Host yggdrasil.borgbase
      HostName nx69hpl8.repo.borgbase.com
      User nx69hpl8
      IdentityFile ${config.sops.secrets."append.borgbase".path}
      IdentitiesOnly yes

      BatchMode yes
      ServerAliveInterval 10
      ServerAliveCountMax 30

      IPQoS cs1
  '';

  checkBorgUnit = {
    serviceConfig = {
      Type = "oneshot";
      ExecStart = "${pkgs.borgbackup}/bin/borg ${utils.escapeSystemdExecArgs [
        "--lock-wait" "3600"
        "--log-json"
        "--progress"
        "check"
        "--verify-data"
        "--max-duration" "4500"
      ]} %I";
      Environment = [
        "BORG_BASE_DIR=/var/lib/borg"
        "BORG_CONFIG_DIR=/var/lib/borg/config"
        "BORG_CACHE_DIR=/var/lib/borg/cache"
        "BORG_SECURITY_DIR=/var/lib/borg/security"
        "BORG_KEYS_DIR=/var/lib/borg/keys"
        "BORG_HOSTNAME_IS_UNIQUE=yes"
        "BORG_RSH=\"${pkgs.openssh}/bin/ssh -F ${pkgs.writeText "config" sshConfig}\""
      ];
    };
  };

  baseDir = "/srv/backup/borg";
in {
  imports = with flakeInputs; [
    prometheus-borg-exporter.nixosModules.default
  ];

  config = {
    services.borgsnap = {
      enable = true;

      target = "yggdrasil.borgbase:repo";
      inherit sshConfig;
      keyfile = config.sops.secrets."yggdrasil.borgkey".path;
    };

    services.copyborg.jotnar = {
      from = "${baseDir}/jotnar";
      to = "yggdrasil.borgbase:repo";
      inherit sshConfig;
      keyfile = config.sops.secrets."yggdrasil.borgkey".path;
      timerOptions.timerConfig = {
        OnCalendar = "*-*-* 00/4:00:00 Europe/Berlin";
      };
    };

    services.borgbackup.repos = {
      jotnar = {
        path = "${baseDir}/jotnar";
        authorizedKeysAppendOnly = let
          dir = ./jotnar;
          toAuthKey = fname: ftype: if ftype != "regular" || !(hasSuffix ".pub" fname) then null else builtins.readFile (dir + "/${fname}");
        in filter (v: v != null) (mapAttrsToList toAuthKey (builtins.readDir dir));
      };
      "uniworx.de" = {
        path = "${baseDir}/uniworx.de";
        authorizedKeys = [
          (builtins.readFile ./uniworx.de/root.pub)
          (builtins.readFile ./uniworx.de/admin.srv02.pub)
        ];
        authorizedKeysAppendOnly = [
          (builtins.readFile ./uniworx.de/append.srv01.pub)
          (builtins.readFile ./uniworx.de/append.srv02.pub)
        ];
      };
    };

    services.prometheus-borg-exporter = {
      enable = true;
      gateway = "localhost:9091";
      target = "yggdrasil.borgbase:repo";
      inherit sshConfig;
      keyfile = config.sops.secrets."yggdrasil.borgkey".path;

      config = {
        job = "yggdrasil.borgbase";
        groups = [
          { regex = "(?P<prefix>yggdrasil\.(surtr|vidhar|niflheim\.ymir))\.(?P<target>.+)-[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}"; }
        ];
      };
    };


    # systemd.services."check-borg@${utils.escapeSystemdPath "${baseDir}/jotnar"}" = checkBorgUnit;
    # systemd.services."check-borg@${utils.escapeSystemdPath "yggdrasil.borgbase:repo"}" = recursiveUpdate checkBorgUnit {
    #   serviceConfig = {
    #     Environment = checkBorgUnit.serviceConfig.Environment ++ [
    #       "BORG_KEY_FILE=${config.sops.secrets."yggdrasil.borgkey".path}"
    #     ];
    #   };
    # };
    # systemd.timers."check-borg@${utils.escapeSystemdPath "${baseDir}/jotnar"}" = {
    #   wantedBy = [ "timers.target" ];
    #   timerConfig = {
    #     OnCalendar = "*-*-* 00:30:00 UTC";
    #   };
    # };
    # systemd.timers."check-borg@${utils.escapeSystemdPath "yggdrasil.borgbase:repo"}" = {
    #   wantedBy = [ "timers.target" ];
    #   timerConfig = {
    #     OnCalendar = "*-*-* 00:30:00 UTC";
    #   };
    # };

    boot.postBootCommands = mkBefore ''
      ${pkgs.findutils}/bin/find ${baseDir} -type d -empty -delete
    '';

    users.users.borg.extraGroups = ["ssh"];

    services.openssh.extraConfig = ''
      Match User borg
        ClientAliveInterval 10
        ClientAliveCountMax 30

      Match All
    '';

    sops.secrets."append.borgbase" = {
      format = "binary";
      sopsFile = ./append.borgbase;
      owner = "borg";
      group = "borg";
      mode = "0400";
    };
    sops.secrets."yggdrasil.borgkey" = {
      format = "binary";
      sopsFile = ./yggdrasil.borgkey;
      owner = "borg";
      group = "borg";
      mode = "0400";
    };
  };
}