{ config, pkgs, lib, inputs, ... }:

# TODO: make /etc/nixos a symlink to the in-store flake? - bad idea, horrible error recovery
# TODO: make /etc/nixos a writeable checkout of repo?

{

  system.autoUpgrade.enable = true;
  #system.autoUpgrade.allowReboot = true; # reboot after a kernel (module) or initrd upgrade, consider also setting `rebootWindow`

  environment.etc."current-system-flake".source = inputs.self;
  # workaround for https://github.com/NixOS/nix/issues/6895
  environment.etc."current-system-flake-inputs.json".source
    = pkgs.writers.writeJSON "flake-inputs.json" (
      lib.flip lib.mapAttrs inputs (name: input:
        # inputs.*.sourceInfo sans outPath, since writeJSON will otherwise serialize sourceInfo like derivation
        lib.filterAttrs (key: val: !builtins.elem key ["outPath"]) (input.sourceInfo or {})
          // { store-path = input.outPath; } # comment this line if you don't want to retain a store reference to the flake inputs
      )
    );

  #system.autoUpgrade.flake = inputs.self.outPath; # a nix store path
  #system.autoUpgrade.flake = "github:pbsds/nix-config"; # TODO: use this instead?
  #system.autoUpgrade.flake = "git+https://gitea.noximilien.pbsds.net/pbsds/config.git";
  system.autoUpgrade.flake = "git+https://git.pvv.ntnu.no/pederbs/config.git";

  system.autoUpgrade.flags = [
    "-L" # print build logs
    "--no-write-lock-file" # no write new flakelock, as the in-store flake is read-only
    "--option" "access-tokens" "" # don't risk an expired github token blocking the upgrade
    # fetch new inputs
    #"--recreate-lock-file" # update all
    #"--override-input" "nixpkgs-edge" # deprecated in nix 2.22, removed in lix 2.90
    "--refresh"
    "--override-input" "nixpkgs-edge" "github:NixOS/nixpkgs/nixos-unstable"
    "--override-input" "nixpkgs-2405" "github:NixOS/nixpkgs/nixos-24.05"
    "--override-input" "nixpkgs-2311" "github:NixOS/nixpkgs/nixos-23.11"
    "--override-input" "home-manager-edge" "github:nix-community/home-manager/master"
    "--override-input" "home-manager-2405" "github:nix-community/home-manager/release-24.05"
    "--override-input" "home-manager-2311" "github:nix-community/home-manager/release-23.11"
    "--override-input" "nix-index-database" "github:Mic92/nix-index-database"
    "--override-input" "nixos-hardware" "github:NixOS/nixos-hardware"
  ];

  # lots of "empty" updates
  boot.loader.grub.configurationLimit = 15;
  boot.loader.systemd-boot.configurationLimit = 15;
  boot.loader.generic-extlinux-compatible.configurationLimit = 15;

}
