#!/usr/bin/env bash

# Deploys the generate_protobuf_descriptors binary package to ZWeb.
# It will be downloaded and installed by the setup script for use in the
# proto_extension_validator.
# Update scripts/ansible/roles/file_validators/tasks/main.yml after running this
# script.

set -euo pipefail

script_directory="$( (builtin cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) )"
project_root="$( ( builtin cd "$script_directory" && git rev-parse --show-toplevel) )"

cd "$project_root"
source scripts/shell/zooxrc.sh

tmp_dir="$(mktemp --directory)"
tar_path="${tmp_dir}/generate_protobuf_descriptors.tar"
tmp_script=${tmp_dir}__extract__${RANDOM}
final_script=${tmp_dir}/generate_protobuf_descriptors

# make the tar
python pipedream/common/archive/bazel_build_archive.py --target=//ci/file_validators/proto_extension:generate_protobuf_descriptors --archive-dest="${tar_path}"

printf '#!/bin/bash
set -euo pipefail
payload="$(awk "/^__PAYLOAD_BELOW__/ {print NR + 1; exit 0; }" $0)"
tmp_dir="$(mktemp --directory)"
tail --lines=+$payload $0 | tar --extract --directory "${tmp_dir}"
"${tmp_dir}/generate_protobuf_descriptors" "$@"
result=$?
rm -rf "${tmp_dir}"
exit ${result}
__PAYLOAD_BELOW__
' > "${tmp_script}"

cat "${tmp_script}" "${tar_path}" > "${final_script}"
rm "${tmp_script}" "${tar_path}"

chmod +x "${final_script}"

uri="s3://zoox-web/ci_file_validators/$(sha256sum "${final_script}" | cut -d ' ' -f 1)/generate_protobuf_descriptors"
aws s3 cp "${final_script}" "${uri}"
echo Uploaded to ${uri}

rm -rf "${tmp_dir}"
