{ inputs }:
let
  inherit (inputs.nixpkgs.lib) filterAttrs mapAttrs';
in
{
  mkExtendedLib =
    flake: nixpkgs:
    nixpkgs.lib.extend (
      _final: _prev: {
        mjallen = flake.mjallen-lib;
      }
    );

  mkNixpkgsConfig = flake: {
    overlays = builtins.attrValues flake.overlays;
    config = {
      allowAliases = false;
      allowUnfree = true;
      permittedInsecurePackages = [
        # Add any permitted insecure packages here
        "mbedtls-2.28.10"
      ];
    };
  };

  mkHomeConfigs =
    {
      flake,
      system,
      hostname,
    }:
    let
      inherit (flake.mjallen-lib.file) scanHomes;
      homesPath = ../../homes;
      allHomes = scanHomes homesPath;
    in
    filterAttrs (
      _name: homeConfig: homeConfig.system == system && homeConfig.hostname == hostname
    ) allHomes;

  mkHomeManagerConfig =
    {
      extendedLib,
      inputs,
      system,
      matchingHomes,
      isNixOS ? true,
    }:
    if matchingHomes != { } then
      {
        home-manager = {
          useGlobalPkgs = true;
          useUserPackages = true;
          extraSpecialArgs = {
            inherit inputs system;
            inherit (inputs) self;
            lib = extendedLib;
          };
          sharedModules = [
            { _module.args.lib = extendedLib; }
          ]
          ++ (extendedLib.mjallen.file.importModulesRecursive ../../modules/home);
          users = mapAttrs' (_name: homeConfig: {
            name = homeConfig.username;
            value = {
              imports = [ homeConfig.path ];
              home = {
                inherit (homeConfig) username;
                homeDirectory = inputs.nixpkgs.lib.mkDefault (
                  if isNixOS then "/home/${homeConfig.username}" else "/Users/${homeConfig.username}"
                );
              };
            }
            // (
              if isNixOS then
                {
                  _module.args.username = homeConfig.username;
                }
              else
                { }
            );
          }) matchingHomes;
        };
      }
    else
      { };

  mkSpecialArgs =
    {
      inputs,
      hostname,
      username,
      extendedLib,
    }:
    {
      inherit inputs hostname username;
      inherit (inputs) self;
      lib = extendedLib;
      namespace = "mjallen";
      format = "system";
      host = hostname;
    };
}
