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

with lib;
let
  cfg = config.my.programs.nix;

  mkSuper = system: nix:
    if cfg.useSuper
    then inputs.nix-super.packages.${system}.default
    else nix;

  mkNom = system: nix:
    if cfg.useNom
    then
      inputs.nix-monitored.packages.${system}.default.override
        {
          withNotify = false;
          nix = nix;
        }
    else nix;

  mkNix = system: nix: mkNom system (mkSuper system nix);
in
{
  options.my.programs.nix = {
    gc = {
      enable = mkEnableOption "nix-gc";
      minimumFreedGB = mkOption {
        default = 32;
        type = types.int;
        apply = number: toString (number * 1024 * 1024 * 1024);
      };
    };
    optimise.enable = mkEnableOption "nix-optimise";
    useSuper = mkEnableOption "use nix super";
    useNom = mkEnableOption "use nix output monitor" // { default = true; };
  };

  config = {
    my.nixpkgs.overlays = [
      (final: prev:
        {
          nixos-rebuild = prev.nixos-rebuild.override {
            nix = mkNom final.system final.nix;
          };
        })
    ];

    home-manager.users.moritz.programs.direnv.nix-direnv.package = pkgs.nix-direnv.override {
      nix = config.nix.package;
    };

    nix = {
      nixPath = [ "nixpkgs=${inputs.nixpkgs}" ];

      package = mkNix pkgs.system pkgs.nix;

      extraOptions = "experimental-features = nix-command flakes";

      gc = {
        automatic = cfg.gc.enable;
        options = "--max-freed ${cfg.gc.minimumFreedGB} --delete-older-than 14d";
        dates = "weekly";
      };

      optimise = {
        automatic = cfg.optimise.enable;
        dates = [ "weekly" ];
      };

      registry = {
        master-upstream.to = {
          type = "github";
          owner = "nixos";
          repo = "nixpkgs";
        };
        master.flake = inputs.master;
        nixpkgs.flake = inputs.nixpkgs;
        stable.flake = inputs.stable;
        dotfiles.flake = self;
        default.flake = self;
      };

      settings = {
        substituters = [
          "https://cache.nixos.org/"
        ];
        trusted-public-keys = [
          "cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="
        ];

        trusted-users = [ "root" "@wheel" ];
      };
    };
  };
}
