# Given a file with a list of chum, this script copies the chum variants to
# a common temp directory, tars it up, uploads the tarball to s3 and generates
# a txt file with a list of new chum uris for use in a unit test.
#
# Example usage:
#   bash sim/sim_tests/smart_agent/scripts/archive_data_for_test.sh sim/log_test_converter/testing/chum_sets/chum_set_small_7.txt

# Exit on any failures.
set -e
# Print commands as they are executed.
set -o xtrace

CHUM_LIST="$1"

base_tmp_chum_dir="$(mktemp -d)"
relative_chum_dir="chum"
chum_dir="$base_tmp_chum_dir/$relative_chum_dir"
test_relative_dir="sim/sim_tests/smart_agent/test_data_dir"

tmp_meta_dir="$(mktemp -d)"
chum_uri_new_variants_csv="${tmp_meta_dir}/chum_uri_new_variant.csv"
chum_uri_list="${tmp_meta_dir}/chum_uri_list.txt"

# Copy the variants over to a single folder and output a csv listing:
#   chum_uri,relative_variant_dir,variant_name
while read chum_uri; do
  output_variant=$(uuidgen)
  bazel run //data/chum/tools:message_copy -- --input_uri "$chum_uri" \
      --output "$chum_dir" --output_variant "$output_variant"
  echo "${chum_uri};${test_relative_dir}/${relative_chum_dir};${output_variant}" >> \
      "$chum_uri_new_variants_csv"
done < $CHUM_LIST

# Create tarball. The tar contains the directory `./$relative_chum_dir`.
tmp_tar_dir="$(mktemp -d)"
tmp_tar="$tmp_tar_dir/test_chum_data.tgz"
tar -czf "$tmp_tar" --directory "$base_tmp_chum_dir" .

# Save out a list of the new chum.
bazel run //sim/sim_tests/smart_agent/utils:replace_variants_cli -- \
  --chum_variant_csv="$chum_uri_new_variants_csv" \
  --output_path="$chum_uri_list"

echo "List of chum uri in tar file: $chum_uri_list"

# Upload the data to s3.
bash scripts/build/upload-test-data.sh "$tmp_tar"
