{
  lib,
  pkgs,
  config,
  ...
}:
with lib;
let
  cfg = config.eboskma.nix-common;
in
{
  options.eboskma.nix-common = {
    enable = mkEnableOption "nix-common";
    remote-builders = mkEnableOption "remote builders";
    cross-systems = mkOption {
      description = "list of systems to cross compile for";
      type = with types; listOf str;
      default = [ ];
    };
    gc-interval = mkOption {
      description = "How often to run nix-collect-garbage";
      type = types.str;
      default = "03:15";
    };
  };

  imports = [
    (mkRemovedOptionModule [
      "eboskma"
      "nix-common"
      "disable-cache"
    ] "The option `disable-cache` is no longer used")
  ];

  config = mkIf cfg.enable {
    # nixpkgs = {
    #   config.allowUnfree = true;
    # };

    nix = {
      # package = pkgs.nixVersions.latest;
      package = pkgs.nixVersions.nix_2_23;

      buildMachines = mkIf cfg.remote-builders [
        {
          hostName = "loki";
          systems = [ "x86_64-linux" ] ++ cfg.cross-systems;
          maxJobs = 8;
          speedFactor = 2;
          supportedFeatures = [
            "kvm"
            "big-parallel"
            "nixos-test"
            "benchmark"
          ];
        }
      ];
      distributedBuilds = cfg.remote-builders;

      settings = {
        auto-optimise-store = true;
        allowed-users = [ "root" ];
        trusted-users = [
          "root"
          "@wheel"
        ];
        substituters = [
          "https://nix-community.cachix.org"
          "https://marcus7070.cachix.org"
          "https://devenv.cachix.org"
          "https://elixir-tools.cachix.org"
        ];

        trusted-public-keys = [
          "nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs="
          "marcus7070.cachix.org-1:JawxHSgnYsgNYJmNqZwvLjI4NcOwrcEZDToWlT3WwXw="
          "devenv.cachix.org-1:w1cLUi8dv3hnoSPGAuibQv+f9TZLr6cv/Hm9XgU50cw="
          "elixir-tools.cachix.org-1:GfK9E139Ysi+YWeS1oNN9OaTfQjqpLwlBaz+/73tBjU="
        ];
        experimental-features = [
          "nix-command"
          "flakes"
          "auto-allocate-uids"
        ];
      };

      gc = {
        automatic = true;
        dates = cfg.gc-interval;
        options = "--delete-older-than 30d";
      };
    };

    boot.binfmt.emulatedSystems = cfg.cross-systems;

    programs.ssh.extraConfig = mkIf cfg.remote-builders ''
      Host loki
        HostName 10.0.0.4
        Port 22
        User builder
        IdentitiesOnly yes
        IdentityFile /root/.ssh/id_builder
    '';
  };
}