#!/usr/bin/env bash

# Script to download zstart from a previously built sha and upload to S3.
# Before uploading zstart to s3 the currently deployed zstart is backed up
# and can be rolled back by running rollback_zstart.sh.

set -euo pipefail

if (( $# != 1 )); then
  script="$(basename "${BASH_SOURCE[0]}")"

  echo "Usage: $script <sha>"
  exit 0
fi

sha="$1"

manifest_file="${sha}.json"
tarball_file="${sha}.tar.gz"
tarball_md5_file="${tarball_file}.md5"

# Download the zstart manifest

aws s3 cp s3://zoox-builds/zstart/manifests/"${manifest_file}" "$manifest_file"

# Get the zstart checksum from the manifest

checksum=`jq -r '.assets[] | select(.identifier == "zstart_tarball") | .checksum' "$manifest_file"`

# Download the zstart tarball with the specified checksum

aws s3 cp s3://zoox-builds/zstart/"${checksum}"/zstart.tar.gz "$tarball_file"

# Backup the current zstart tarball and MD5 hash

aws s3 cp s3://zoox-web/zstart/zstart-tarball s3://zoox-web/zstart/zstart-tarball.bak
aws s3 cp s3://zoox-web/zstart/zstart-tarball.md5 s3://zoox-web/zstart/zstart-tarball.md5.bak

# Copy the zstart tarball and its MD5 hash to S3

md5sum "$tarball_file" | awk '{ print $1 }' > "$tarball_md5_file"

aws s3 cp "$tarball_file" s3://zoox-web/zstart/zstart-tarball
aws s3 cp "$tarball_md5_file" s3://zoox-web/zstart/zstart-tarball.md5

# Copy the zstart install script and its MD5 hash to S3

md5sum install-zstart | awk '{ print $1 }' > install-zstart.md5

aws s3 cp install-zstart s3://zoox-web/zstart/install-zstart
aws s3 cp install-zstart.md5 s3://zoox-web/zstart/install-zstart.md5

# Cleanup

rm "$manifest_file"
rm "$tarball_file"
rm "$tarball_md5_file"
rm install-zstart.md5
