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

with lib;

let
  cfg = config.system.copySysConf;
  cfgPath = ../.;
  copySysConf = if !(isStorePath cfgPath) then pkgs.stdenv.mkDerivation rec {
    name = "NixOS_Configuration-${version}";
    version = commitIdFromGitRepo (cfgPath + "/.git");

    src = cleanSource cfgPath;

    installPhase = ''
      cp -R ./. $out
    '';
  } else (builtins.toPath ../.);

in {
  options.system.copySysConf = {
    enable = mkOption {
      type = types.bool;
      description = ''
        Wether to copy the systems configuration.
      '';
    };
    addToNixPath = mkOption {
      type = types.bool;
      description = ''
        Use backup for nixos-rebuild.
      '';
    };
  };

  config = mkIf cfg.enable {
    environment.variables = {
      NIXOS_CONFIG_PATH = "${copySysConf}";
    };
    nix = mkIf cfg.addToNixPath {
      # Do not use lib.optionals as it would override the default nixPath
      nixPath = [
        "nixpkgs=/nix/var/nix/profiles/per-user/root/channels/nixos"
        "nixos-config=${copySysConf}/configuration.nix"
        "/nix/var/nix/profiles/per-user/root/channels"
      ];
    };
  };
}