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 = lib.mdDoc ''
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
46 then [
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 defaultText = ''
53 if nix.channel.enable
54 then [
55 "nixpkgs=/nix/var/nix/profiles/per-user/root/channels/nixos"
56 "nixos-config=/etc/nixos/configuration.nix"
57 "/nix/var/nix/profiles/per-user/root/channels"
58 ]
59 else [];
60 '';
61 description = lib.mdDoc ''
62 The default Nix expression search path, used by the Nix
63 evaluator to look up paths enclosed in angle brackets
64 (e.g. `<nixpkgs>`).
65 '';
66 };
67 };
68
69 system = {
70 defaultChannel = mkOption {
71 internal = true;
72 type = types.str;
73 default = "https://nixos.org/channels/nixos-23.11";
74 description = lib.mdDoc "Default NixOS channel to which the root user is subscribed.";
75 };
76 };
77 };
78
79 config = mkIf cfg.enable {
80
81 environment.extraInit =
82 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 nix.settings.nix-path = mkIf (! cfg.channel.enable) (mkDefault "");
99
100 systemd.tmpfiles.rules = lib.mkIf cfg.channel.enable [
101 ''f /root/.nix-channels - - - - ${config.system.defaultChannel} nixos\n''
102 ];
103 };
104}