#!/usr/bin/env bash
set -e

# The script computes the b2sum of the wasm blob in a pre-built joystream/node image
# Specifically amd64 architecture image, as that is what we use as the "reference" images
# for deterministic builds.
# Assumes b2sum is already instally on the host machine.

SCRIPT_PATH=`dirname "${BASH_SOURCE[0]}"`
cd $SCRIPT_PATH

CODE_SHASUM=`./runtime-code-shasum.sh`
IMAGE=joystream/node:${CODE_SHASUM}

IMG_ARCH=`docker inspect ${IMAGE} --format='{{.Architecture}}'`

if [ "$IMG_ARCH" != "amd64" ]; then
    echo "You must fetch the amd64 architecture image with following command:"
    echo "docker image rm ${IMAGE}"
    echo "docker pull ${IMAGE} --platform amd64"
    exit 1
fi

# Create a non running container from joystream/node using the amd64
docker create --name temp-container-joystream-node ${IMAGE} --platform amd64

# Copy the compiled wasm blob from the docker container to our host
docker cp temp-container-joystream-node:/joystream/runtime.compact.compressed.wasm joystream_runtime.wasm
docker rm temp-container-joystream-node

# compute blake2_256 hash of the wasm blob - this should match the hash computed when the runtime file is
# used to create a runtime upgrade proposal.
# osx with: brew install b2sum; b2sum -b blake2b -l 256 joystream_runtime.wasm
# ubuntu 17.0+ with: apt-get install coreutils; b2sum -l 256 joystream_runtime.wasm
# TODO: add install of b2sum to setup.sh
b2sum -l 256 joystream_runtime.wasm
b2sum -l 512 joystream_runtime.wasm
rm joystream_runtime.wasm
