1#! @runtimeShell@
2
3set -e
4
5# Re-exec ourselves in a private mount namespace so that our bind
6# mounts get cleaned up automatically.
7if [ -z "$NIXOS_ENTER_REEXEC" ]; then
8 export NIXOS_ENTER_REEXEC=1
9 if [ "$(id -u)" != 0 ]; then
10 extraFlags="-r"
11 fi
12 exec unshare --fork --mount --uts --mount-proc --pid $extraFlags -- "$0" "$@"
13else
14 mount --make-rprivate /
15fi
16
17mountPoint=/mnt
18system=/nix/var/nix/profiles/system
19command=("$system/sw/bin/bash" "--login")
20silent=0
21
22while [ "$#" -gt 0 ]; do
23 i="$1"; shift 1
24 case "$i" in
25 --root)
26 mountPoint="$1"; shift 1
27 ;;
28 --system)
29 system="$1"; shift 1
30 ;;
31 --help)
32 exec man nixos-enter
33 exit 1
34 ;;
35 --command|-c)
36 command=("$system/sw/bin/bash" "-c" "$1")
37 shift 1
38 ;;
39 --silent)
40 silent=1
41 ;;
42 --)
43 command=("$@")
44 break
45 ;;
46 *)
47 echo "$0: unknown option \`$i'"
48 exit 1
49 ;;
50 esac
51done
52
53if [[ ! -e $mountPoint/etc/NIXOS ]]; then
54 echo "$0: '$mountPoint' is not a NixOS installation" >&2
55 exit 126
56fi
57
58mkdir -p "$mountPoint/dev" "$mountPoint/sys"
59chmod 0755 "$mountPoint/dev" "$mountPoint/sys"
60mount --rbind /dev "$mountPoint/dev"
61mount --rbind /sys "$mountPoint/sys"
62
63(
64 # If silent, write both stdout and stderr of activation script to /dev/null
65 # otherwise, write both streams to stderr of this process
66 if [ "$silent" -eq 1 ]; then
67 exec 2>/dev/null
68 fi
69
70 # Run the activation script. Set $LOCALE_ARCHIVE to supress some Perl locale warnings.
71 LOCALE_ARCHIVE="$system/sw/lib/locale/locale-archive" chroot "$mountPoint" "$system/activate" 1>&2 || true
72
73 # Create /tmp
74 chroot "$mountPoint" systemd-tmpfiles --create --remove --exclude-prefix=/dev 1>&2 || true
75)
76
77exec chroot "$mountPoint" "${command[@]}"