#!/usr/bin/env bash
set -euo pipefail

script_dir="$(builtin cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

image=emscripten-packaging
container="$image-$(openssl rand -hex 4)"

echo Installing emscripten in docker image $image
docker build "$script_dir" --rm --tag="$image"

root="$(mktemp --directory)"
staging="$root/staging/emscripten"
package="$root/emscripten.tar.gz"

echo Copying installed files to staging directory $staging
mkdir --parents "$staging" "$staging/rpath"
docker create --name="$container" "$image"
docker cp "$container:/opt/emsdk/node/12.18.1_64bit" "$staging/node"
docker cp "$container:/opt/emsdk/upstream" "$staging/upstream"
docker cp "$container:/usr/lib/x86_64-linux-gnu/libstdc++.so.6" "$staging/rpath"
docker cp "$container:/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21" "$staging/rpath"
docker rm --force "$container"

echo Packaging installed files to $package
tar \
  --create \
  --gzip \
  --file="$package" \
  --directory="$(dirname "$staging")" \
  "$(basename "$staging")"
