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

let
  inherit (builtins) elem;
  cfg = config.local.nix;

  gitple = "https://git.pleshevski.ru";
  mkRegistry = id: url: {
    from = { type = "indirect"; inherit id; };
    to = { type = "git"; inherit url; };
  };
in
{
  options.local.nix = with lib; {
    enableMyRegistry = mkOption {
      type = types.bool;
      default = false;
      description = "Enable my custom nix registry";
    };
    allowUnfreePackages = mkOption {
      type = types.listOf types.str;
      default = [ ];
    };
  };

  config = {
    environment.systemPackages =
      lib.optional config.system.tools.nixos-option.enable pkgs.unstable.nixos-option;

    nixpkgs.config.allowUnfreePredicate = lib.mkIf
      (cfg.allowUnfreePackages != [ ])
      (pkg: elem (lib.getName pkg) cfg.allowUnfreePackages);

    nixpkgs.overlays = lib.mkBefore [
      (final: prev: {
        image-roll = prev.image-roll.override {
          rustPlatform = prev.rustPlatform // {
            buildRustPackage = args:
              prev.rustPlatform.buildRustPackage (args // {
                checkFlags = args.checkFlags ++ [
                  # Image type “ico” is not supported
                  "--skip=image::tests::save_image_uses_extensions_for_file_types_supported_by_pixbuf_save"
                ];
              });
          };
        };
      })
      (final: prev: {
        sniffnet = (import inputs.nixpkgs-unstable {
          inherit (config.nixpkgs) config system;
        }).sniffnet;
      })
      (final: prev: {
        unstable = import inputs.nixpkgs-unstable {
          inherit (config.nixpkgs) config overlays system;
        };
      })
    ];

    nix = {
      settings = {
        auto-optimise-store = true;

        trusted-users = [ "root" ];

        experimental-features = [ "nix-command" "flakes" ];
      };

      registry = lib.mkMerge [
        {
          nixpkgs.flake = inputs.nixpkgs;
          nixpkgs-unstable.flake = inputs.nixpkgs-unstable;
        }

        (lib.mkIf cfg.enableMyRegistry {
          templates = mkRegistry "tmpl" "${gitple}/mynix/templates";
          tools = mkRegistry "tools" "${gitple}/mynix/tools";
        })
      ];
    };
  };
}