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

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 = {
    nixpkgs.config.allowUnfreePredicate = lib.mkIf
      (cfg.allowUnfreePackages != [ ])
      (pkg: elem (lib.getName pkg) cfg.allowUnfreePackages);

    nixpkgs.overlays = lib.mkBefore [
      (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" ];

        # To protect nix-shell against garbage collection
        # Source: https://github.com/nix-community/nix-direnv#installation
        keep-derivations = true;
        keep-outputs = true;
      };

      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";
        })
      ];
    };
  };
}
