@@ -343,16 +343,6 @@ if [[ -z $flake && -e /etc/nixos/flake.nix ]]; then
343343 flake="$(dirname "$(readlink -f /etc/nixos/flake.nix)")"
344344fi
345345
346−# Re-execute nixos-rebuild from the Nixpkgs tree.
347−# FIXME: get nixos-rebuild from $flake.
348−if [[ -z $_NIXOS_REBUILD_REEXEC && -n $canRun && -z $fast && -z $flake ]]; then
349− if p=$(runCmd nix-build --no-out-link --expr 'with import <nixpkgs/nixos> {}; config.system.build.nixos-rebuild' "${extraBuildFlags[@]}"); then
350− export _NIXOS_REBUILD_REEXEC=1
351− runCmd exec "$p/bin/nixos-rebuild" "${origArgs[@]}"
352− exit 1
353− fi
354−fi
355−
356346# For convenience, use the hostname as the default configuration to
357347# build from the flake.
358348if [[ -n $flake ]]; then
@@ -371,6 +361,40 @@ if [[ -n $flake ]]; then
371361 fi
372362fi
373363
364+
365+tmpDir=$(mktemp -t -d nixos-rebuild.XXXXXX)
366+
367+cleanup() {
368+ for ctrl in "$tmpDir"/ssh-*; do
369+ ssh -o ControlPath="$ctrl" -O exit dummyhost 2>/dev/null || true
370+ done
371+ rm -rf "$tmpDir"
372+}
373+trap cleanup EXIT
374+
375+
376+# Re-execute nixos-rebuild from the Nixpkgs tree.
377+if [[ -z $_NIXOS_REBUILD_REEXEC && -n $canRun && -z $fast ]]; then
378+ if [[ -z $flake ]]; then
379+ if p=$(runCmd nix-build --no-out-link --expr 'with import <nixpkgs/nixos> {}; config.system.build.nixos-rebuild' "${extraBuildFlags[@]}"); then
380+ SHOULD_REEXEC=1
381+ fi
382+ else
383+ runCmd nix "${flakeFlags[@]}" build --out-link "${tmpDir}/nixos-rebuild" "$flake#$flakeAttr.config.system.build.nixos-rebuild" "${extraBuildFlags[@]}" "${lockFlags[@]}"
384+ if p=$(readlink -e "${tmpDir}/nixos-rebuild"); then
385+ SHOULD_REEXEC=1
386+ fi
387+ fi
388+
389+ if [[ -n $SHOULD_REEXEC ]]; then
390+ export _NIXOS_REBUILD_REEXEC=1
391+ # Manually call cleanup as the EXIT trap is not triggered when using exec
392+ cleanup
393+ runCmd exec "$p/bin/nixos-rebuild" "${origArgs[@]}"
394+ exit 1
395+ fi
396+fi
397+
374398# Find configuration.nix and open editor instead of building.
375399if [ "$action" = edit ]; then
376400 if [[ -z $flake ]]; then
@@ -385,19 +409,8 @@ if [ "$action" = edit ]; then
385409 exit 1
386410fi
387411
388−
389−tmpDir=$(mktemp -t -d nixos-rebuild.XXXXXX)
390412SSHOPTS="$NIX_SSHOPTS -o ControlMaster=auto -o ControlPath=$tmpDir/ssh-%n -o ControlPersist=60"
391413
392−cleanup() {
393− for ctrl in "$tmpDir"/ssh-*; do
394− ssh -o ControlPath="$ctrl" -O exit dummyhost 2>/dev/null || true
395− done
396− rm -rf "$tmpDir"
397−}
398−trap cleanup EXIT
399−
400−
401414# First build Nix, since NixOS may require a newer version than the
402415# current one.
403416if [[ -n "$rollback" || "$action" = dry-build ]]; then