#!/usr/bin/env bash

set -euo pipefail

# Directory where outputs will show up.
output_directory=$(mktemp --directory)
# Directory in the container to put outputs.
container_output_directory=/home/zoox/out
valgrind_version=3.15.0
image=docker-registry.zooxlabs.com/driving:45

echo Output directory: $output_directory
chmod 777 "$output_directory"

# While not an output, it is convenient to put the build script in the shared
# output directory.
cat <<SCRIPT > "$output_directory"/make.sh
#!/usr/bin/env bash

set -euo pipefail

build_dir="$container_output_directory"/build
mkdir "\$build_dir"
cd "\$(mktemp --directory)"

wget https://sourceware.org/pub/valgrind/valgrind-"$valgrind_version".tar.bz2 --output-document valgrind.tar.bz2
bunzip2 valgrind.tar.bz2
tar -xf valgrind.tar
cd valgrind-"$valgrind_version"

./configure prefix="\$build_dir"
make --jobs 20

DEST_DIR="\$build_dir" make install

tar --create --gzip --file "$container_output_directory"/valgrind-"$valgrind_version".tar.gz --directory "\$build_dir" ./
SCRIPT

# Mount the output directory so the build script is accessible to the container
# and the container can copy the artifacts back to the host.
docker run \
  --rm \
  --mount type=bind,source="$output_directory",target="$container_output_directory" \
  "$image" \
  bash "$container_output_directory"/make.sh

cat <<RESULTS
Tar created: $output_directory/valgrind-$valgrind_version.tar.gz

Run \`scripts/build/upload-to-third-party.sh $output_directory/valgrind-$valgrind_version.tar.gz\`
to upload it for use.
RESULTS
