{ config, lib, ... }:
{

  options.system.image.updates = {
    enable = lib.mkEnableOption "system updates via systemd-sysupdate" // {
      default = config.system.image.updates.url != null;
    };
    url = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = null;
    };
  };

  config = lib.mkIf config.system.image.updates.enable {

    assertions = [
      { assertion = config.system.image.updates.url != null; }
    ];

    systemd.additionalUpstreamSystemUnits = [
      "systemd-bless-boot.service"
      "boot-complete.target"
      "dbus-org.freedesktop.sysupdate1.service"
      "systemd-sysupdated.service"
    ];

    environment.etc."sysupdate.d/10-uki.transfer" = {
      text = ''
        [Source]
        Path=${config.system.image.updates.url}
        MatchPattern=${config.boot.uki.name}_@v.efi
        Type=url-file

        [Target]
        InstancesMax=2
        MatchPattern=${config.boot.uki.name}_@v+@l-@d.efi ${config.boot.uki.name}_@v+@l.efi ${config.boot.uki.name}_@v.efi
        Mode=0444
        Path=/EFI/Linux
        PathRelativeTo=esp
        TriesDone=0
        TriesLeft=3
        Type=regular-file

        [Transfer]
        Verify=no
        '';
    };

    environment.etc."sysupdate.d/20-root.transfer" = {
      text = ''
        [Source]
        Type=url-file
        Path=${config.system.image.updates.url}
        MatchPattern=${config.system.image.id}_@v_@u.verity

        [Target]
        Type=partition
        Path=auto
        MatchPattern=verity-@v
        MatchPartitionType=root-verity
        ReadOnly=1

        [Transfer]
        Verify=no
        '';
    };

    environment.etc."sysupdate.d/22-root.transfer" = {
      text = ''
        [Source]
        Type=url-file
        Path=${config.system.image.updates.url}
        MatchPattern=${config.system.image.id}_@v_@u.root

        [Target]
        Type=partition
        Path=auto
        MatchPattern=root-@v
        MatchPartitionType=root
        ReadOnly=1

        [Transfer]
        Verify=no
        '';
    };

  };

}