#!/usr/bin/env bash

# Uploads the given file to Z3 and S3.
# Note: Run //scripts/build:init_z3_profile if you don't have
# Z3 credentials configured.

set -euo pipefail

bucket_name="$1"
file_path="$2"
file_name=$(basename "$file_path")

# Use awk to remove the filename that sha256sum likes printing out so much.
sha_256="$(sha256sum "$file_path" | awk '{print $1}')"
z3_path="s3://$bucket_name/${sha_256}/${file_name}"
url="https://z3.zooxlabs.com/$bucket_name/${sha_256}/${file_name}"
s3_url="https://s3-us-west-1.amazonaws.com/$bucket_name/${sha_256}/${file_name}"

# Upload to Z3.
if ! aws s3 \
  --endpoint-url=https://z3.zooxlabs.com \
  --profile=z3 \
  cp "$file_path" "$z3_path" \
  --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers; then
  echo Upload to Z3 failed!
  echo Try running `bazel run //scripts/build:init_z3_profile` to install the
  echo credentials and try this command again.
  echo
  echo Alternatively, run 'aws configure set profile.z3.s3.signature_version s3'
  echo to resolve signature mismatch errors.
  exit 1
fi

# Upload to S3 as a backup.
aws s3 \
  cp "$file_path" "$z3_path" \
  --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers

cat <<MESSAGE
File uploaded!

Z3 URI: $z3_path
Z3 HTTPS URL: $url
S3 HTTPS URL: $s3_url
SHA256: $sha_256
MESSAGE

if [[ $bucket_name == zoox-testdata ]]; then
  cat <<MESSAGE

Use in a BUILD file like so:

load("//build:z3.bzl", "z3_test_data")

z3_test_data(
    name = "$file_name",
    sha256 = "$sha_256",
)
MESSAGE
fi
