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