{ lib, config, pkgs, utils, ... }:
let
  cfg = config.backup-helper;
  escaped-path = "/etc/machine-id";
  restic-wrapper = pkgs.writeShellApplication {
    name = "restic-wrapper";
    runtimeInputs = [
      pkgs.restic
      pkgs.systemd
    ];
    text = ''
      if [ "$#" -ne 1 ]; then
        echo "Need exactly one argument, the path to backup.";
        exit 1;
      fi
      path="$1";
      echo "Starting backup of $path";
      # restic backup ${escaped-path};
    '';
  };
in
{
  options.backup-helper.enable = lib.mkEnableOption "Enable backup-helper";
  options.backup-helper = {
    restic-repository = lib.mkOption {
      type = lib.types.str;
      default = "rest:http://10.69.12.52:8000/backup-nix";
      description = "Repository to use for restic backup.";
    };
    backup-dirs = lib.mkOption {
      type = lib.types.listOf lib.types.str;
      default = [ ];
      description = "Directories to be backed up.";
    };
    schedule = lib.mkOption {
      type = lib.types.str;
      default = "*-*-* 00:00:00";
      description = "Schedule for backups. Needs to be valid systemd OnCalendar value.";
    };
    password-file = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = null;
      description = "File containing the restic password.";
    };
    randomized-delay = lib.mkOption {
      type = lib.types.int;
      default = 0;
      description = "Randomized delay in seconds to spread out backups.";
    };
  };
  config = lib.mkIf cfg.enable {
    systemd.services."backup-helper@" = {
      after = [ "network-online.target" ];
      environment = {
        RESTIC_REPOSITORY = cfg.restic-repository;
      } // lib.attrsets.optionalAttrs (builtins.hasAttr "password-file" cfg) {
        RESTIC_PASSWORD_FILE = cfg.password-file;
      };
      serviceConfig = {
        Type = "oneshot";
        ExecStart = "${restic-wrapper}/bin/restic-wrapper %f";
      };
    };
    systemd.timers."backup-helper@" = {
      timerConfig = {
        OnCalendar = cfg.schedule;
        Persistent = true;
        RandomizedDelaySec = cfg.randomized-delay;
      };
    };
    systemd.timers.${escaped-path} = {
      wantedBy = [ "timers.target" ];
      overrideStrategy = "asDropin";
    };
  };
}