#!/bin/bash
# Script for updating the linux-arm64 release
#
# Takes as stdin the JSON string generated by the S3 bucket update when
# amazon produces a new build. e.g.
# {"Records":[{"eventVersion":"2.1","eventSource":"aws:s3","awsRegion":"us-west-2","eventTime":"2023-08-23T19:12:29.218Z","eventName":"ObjectCreated:CompleteMultipartUpload","userIdentity":{"principalId":"AWS:AROAZNAVTCTIWSHR6WFTE:i-0124c978819146a2f"},"requestParameters":{"sourceIPAddress":"35.90.239.236"},"responseElements":{"x-amz-request-id":"3SDMWYMG4BN47DCD","x-amz-id-2":"0mRaqwIIZI8ob1B7TmTSd/s0lXxST73ktgGm94MjKj2bnflqD1zCjbh2LeMIYYPvvfgQu0Ocrlev4nYmiOmS9wR0M/lvpCQz"},"s3":{"s3SchemaVersion":"1.0","configurationId":"arn:aws:cloudformation:us-west-2:646437868753:stack/EmscriptenArm64BuilderStack/eb5d5760-ee9a-11ec-a790-06738944b93b--3752220361625282518","bucket":{"name":"emscripten-arm64-4484191c","ownerIdentity":{"principalId":"A2IEUDOSUKZVHO"},"arn":"arn:aws:s3:::emscripten-arm64-4484191c"},"object":{"key":"emscripten-install-3.1.45-linux-arm64.tbz2","size":247058408,"eTag":"bb7f6835c7900deee6e7881a352ab48c-30","sequencer":"0064E65A1BC2C23A2E"}}}]}

set -e

if [ $# -ne 1 ]; then
  echo "Please specify a single argument which is an emsdk version (e.g. 3.1.45)"
  exit
fi

VERSION=$1
SHA=$(jq -r ".releases.\"${VERSION}\"" emscripten-releases-tags.json)
URL=$(jq -r '.Records[0] | "https://\(.s3.bucket.name).s3.\(.awsRegion).amazonaws.com/\(.s3.object.key)"')

wget $URL -O arm64.tar.xz
gsutil cp -n arm64.tar.xz gs://webassembly/emscripten-releases-builds/linux/${SHA}/wasm-binaries-arm64.tar.xz
sed -i "s/\"latest-arm64-linux\": \".*\"/\"latest-arm64-linux\": \"$VERSION\"/" emscripten-releases-tags.json

echo "done"
