{ config, pkgs, ... }:
let
  microvms = {
    staging-data-hoarder.flakeref = "git+https://github.com/tlm-solutions/nix-config";
  };
in
{
  microvm.autostart = builtins.attrNames microvms;

  systemd.services = {

    "microvm-update@" = {
      description = "Update MicroVMs automatically";
      after = [ "network-online.target" ];
      unitConfig.ConditionPathExists = "/var/lib/microvms/%i";
      serviceConfig = {
        Type = "oneshot";
      };
      path = with pkgs; [ nix git ];
      environment.HOME = config.users.users.root.home;
      scriptArgs = "%i";
      script = ''
        NAME=$1
        /run/current-system/sw/bin/microvm -Ru $NAME
      '';
    };

  } // builtins.foldl' (services: name: services // {
    "microvm-create-${name}" = {
      description = "Create MicroVM ${name} automatically";
      wantedBy = [ "microvms.target" ];
      after = [ "network-online.target" ];
      before = [
        "microvm-tap-interfaces@${name}.service"
        "microvm-virtiofsd@${name}.service"
      ];
      unitConfig.ConditionPathExists = "!/var/lib/microvms/${name}";
      serviceConfig.Type = "oneshot";
      path = [ pkgs.git ];
      environment.HOME = config.users.users.root.home;
      scriptArgs = "${name}";
      script = ''
        /run/current-system/sw/bin/microvm -c ${name} -f "${microvms.${name}.flakeref}"
      '';
    };
  }) {} (builtins.attrNames microvms);

  systemd.timers = builtins.foldl' (timers: name: timers // {
    "microvm-update-${name}" = {
      wantedBy = [ "timers.target" ];
      timerConfig = {
        Unit = "microvm-update@${name}.service";
        # three times per hour
        OnCalendar = "*:0,20,40:00";
        Persistent = true;
      };
    };
  }) {} (builtins.attrNames microvms);
}
