Use out/fidlbolt build directory in prepare_deployment.sh

This CL makes prepare_deployment.sh run 'fx set core.x64 --release' in a
separate Fuchsia build directory, out/fidlbolt. This makes it easier to
deploy without interfering with other work, and eliminates the chance of
accidentally deploying the wrong build (e.g. a debug build).

Change-Id: Ifa1474db8d954aafb22f5a59737d2a13f7afec88
Reviewed-on: https://fuchsia-review.googlesource.com/c/fidlbolt/+/584263
Reviewed-by: Yifei Teng <yifeit@google.com>
diff --git a/prepare_deployment.sh b/prepare_deployment.sh
index 91b5831..c3bfca0 100755
--- a/prepare_deployment.sh
+++ b/prepare_deployment.sh
@@ -8,11 +8,10 @@
 
 This script prepares for a fidlbolt deployment. It:
 
-1. Builds needed targets in $FUCHSIA_DIR.
+1. Builds needed targets in \$FUCHSIA_DIR/out/fidlbolt.
 
-   This assumes you have fuchsia, and nested repositories like topaz, in the
-   state you want them. It will warn if there are uncommitted changes or if the
-   commit has not been merged on the remote.
+   This assumes you have fuchsia.git in the desired state. It will warn if there
+   are uncommitted changes or if the commit has not been merged on the remote.
 
 2. Copies binaries and other files into ./deployment.
 
@@ -69,7 +68,7 @@
 fi
 
 # Source fx-env.sh to get the fx tool on the PATH.
-# Source vars.sh for FUCHSIA_BUILD_DIR and PREBUILT_RUST_DIR.
+# Source vars.sh for PREBUILT_RUST_DIR.
 # (Reset shell options before sourcing since vars.sh does not expect them.)
 set +ufo pipefail
 source "$FUCHSIA_DIR/scripts/fx-env.sh" || exit $?
@@ -77,6 +76,9 @@
 fx-config-read
 set -ufo pipefail
 
+# Unset this vars.sh variable since we invalidate it below with `fx --dir`.
+unset FUCHSIA_BUILD_DIR
+
 readonly binaries=(
     "fidl-format"
     "fidl-lint"
@@ -88,10 +90,19 @@
     "fidlgen_rust"
 )
 
-step "Building targets in $FUCHSIA_DIR"
-pushd "$FUCHSIA_DIR"
-fx build "${binaries[@]/#/host_x64/}"
-popd
+readonly old_build_dir=$(< "$FUCHSIA_DIR/.fx-build-dir")
+readonly rel_build_dir="out/fidlbolt"
+readonly build_dir="$FUCHSIA_DIR/$rel_build_dir"
+
+step "Building targets in $build_dir"
+cd "$FUCHSIA_DIR"
+# Save the build status to prevent an early exit from `set -e` upon failure, so
+# that we can restore the old build directory before exiting.
+build_status=0
+fx --dir "$rel_build_dir" set bringup.x64 --release || build_status=$?
+fx build "${binaries[@]/#/host_x64/}" || build_status=$?
+fx use "$old_build_dir"
+[[ "$build_status" -ne 0 ]] && exit "$build_status"
 
 step "Cleaning ./deployment"
 cd "$(dirname "$0")"
@@ -99,7 +110,7 @@
 mkdir -p deployment/{bin,etc,fuchsia/{sdk/fidl,zircon}}
 
 step "Copying binaries"
-cp "${binaries[@]/#/$FUCHSIA_BUILD_DIR/host_x64/}" \
+cp "${binaries[@]/#/$build_dir/host_x64/}" \
     "$PREBUILT_CLANG_DIR/bin/clang-format" \
     "$PREBUILT_RUST_DIR/bin/rustfmt" \
     deployment/bin