#!/bin/bash

set -euo pipefail

package_json="$1"
output_tar_file="$PWD/$2"
npm_run_directory=$(dirname "$package_json")
log_output_file=$(mktemp)

cd "$npm_run_directory"

function install {
  npm install
  npm run build

  if [ ! -d "build" ]; then
    echo "Did not find build direcotry in: $PWD"
    exit 1
  fi

  cd build

  tar --create --file "$output_tar_file" ./
}

# Run the install but capture the output so we only print it if there is an
# error.
set +e
(
  set -e
  install > "$log_output_file" 2>&1
)
exit_status="$?"
set -e

if [[ "$exit_status" != 0 ]]; then
  cat "$log_output_file"
fi

exit "$exit_status"
