1/*
2 Manages the things that are needed for a traditional nix-channel based
3 configuration to work.
4
5 See also
6 - ./nix.nix
7 - ./nix-flakes.nix
8*/
9{ config, lib, ... }:
10let
11 inherit (lib)
12 mkDefault
13 mkIf
14 mkOption
15 stringAfter
16 types
17 ;
18
19 cfg = config.nix;
20
21in
22{
23 options = {
24 nix = {
25 channel = {
26 enable = mkOption {
27 description = ''
28 Whether the `nix-channel` command and state files are made available on the machine.
29
30 The following files are initialized when enabled:
31 - `/nix/var/nix/profiles/per-user/root/channels`
32 - `/root/.nix-channels`
33 - `$HOME/.nix-defexpr/channels` (on login)
34
35 Disabling this option will not remove the state files from the system.
36 '';
37 type = types.bool;
38 default = true;
39 };
40 };
41
42 nixPath = mkOption {
43 type = types.listOf types.str;
44 default =
45 if cfg.channel.enable then
46 [
47 "nixpkgs=/nix/var/nix/profiles/per-user/root/channels/nixos"
48 "nixos-config=/etc/nixos/configuration.nix"
49 "/nix/var/nix/profiles/per-user/root/channels"
50 ]
51 else
52 [ ];
53 defaultText = ''
54 if nix.channel.enable
55 then [
56 "nixpkgs=/nix/var/nix/profiles/per-user/root/channels/nixos"
57 "nixos-config=/etc/nixos/configuration.nix"
58 "/nix/var/nix/profiles/per-user/root/channels"
59 ]
60 else [];
61 '';
62 description = ''
63 The default Nix expression search path, used by the Nix
64 evaluator to look up paths enclosed in angle brackets
65 (e.g. `<nixpkgs>`).
66 '';
67 };
68 };
69
70 system = {
71 defaultChannel = mkOption {
72 internal = true;
73 type = types.str;
74 default = "https://nixos.org/channels/nixos-unstable";
75 description = "Default NixOS channel to which the root user is subscribed.";
76 };
77 };
78 };
79
80 config = mkIf cfg.enable {
81
82 environment.extraInit = mkIf cfg.channel.enable ''
83 if [ -e "$HOME/.nix-defexpr/channels" ]; then
84 export NIX_PATH="$HOME/.nix-defexpr/channels''${NIX_PATH:+:$NIX_PATH}"
85 fi
86 '';
87
88 environment.extraSetup = mkIf (!cfg.channel.enable) ''
89 rm --force $out/bin/nix-channel
90 '';
91
92 # NIX_PATH has a non-empty default according to Nix docs, so we don't unset
93 # it when empty.
94 environment.sessionVariables = {
95 NIX_PATH = cfg.nixPath;
96 };
97
98 systemd.tmpfiles.rules = lib.mkIf cfg.channel.enable [
99 ''f /root/.nix-channels - - - - ${config.system.defaultChannel} nixos\n''
100 ];
101
102 system.activationScripts.no-nix-channel = mkIf (!cfg.channel.enable) (
103 stringAfter [ "etc" "users" ] (builtins.readFile ./nix-channel/activation-check.sh)
104 );
105 };
106}