#!/usr/bin/env bash

build_dir=$1
cache_basedir=$2
bp_dir=$(cd $(dirname $0); cd ..; pwd)

source $bp_dir/bin/common.sh

# Output npm debug info on error
trap cat_npm_debug_log ERR

# Is a node version specified in package.json?
semver_range=$(cat $build_dir/package.json | $bp_dir/vendor/json engines.node)

# Resolve node version using a service
node_version=$(curl --silent https://node-semver-service.heroku.com/${semver_range})

# Warn if engines.node is unspecified
if ! test $semver_range; then
  echo
  echo "WARNING: No node version specified in package.json, see:" | indent
  echo "https://devcenter.heroku.com/articles/nodejs-support#versions" | indent
  echo
  status "Defaulting to latest stable node, v$node_version"
fi

# TODO: Warn if engines.node is "*" or ">foo"

# Download and install node
status "Downloading and installing node v$node_version"
download_and_install_node $node_version

# Run subsequent node/npm commands from the build path
cd $build_dir

# Configure cache directory
package_checksum=$(cat $build_dir/package.json | md5sum | awk '{print $1}')
cache_dir="$cache_basedir/$package_checksum"

# Restore from cache package.json hasn't changed
if test -d $cache_dir; then
  status "package.json unchanged since last build"
  status "Restoring node_modules from cache"
  test -d $cache_dir/node_modules && cp -r $cache_dir/node_modules $build_dir/
  # cp -r $cache_dir/vendor/node $build_dir/vendor/
else

  status "Installing dependencies"
  npm install --production | indent

  status "Rebuilding dependencies"
  npm rebuild | indent

  status "Caching node_modules for future builds"
  rm -rf $cache_dir
  mkdir -p $cache_dir
  mkdir -p $cache_dir/vendor
  test -d $build_dir/node_modules && cp -r $build_dir/node_modules $cache_dir/
  # cp -r $build_dir/vendor/node $cache_dir/vendor/
fi

# Update the PATH
status "Building runtime environment"
mkdir -p $build_dir/.profile.d
echo "export PATH=\"\$HOME/vendor/node/bin:\$HOME/bin:\$HOME/node_modules/.bin:\$PATH\"" > $build_dir/.profile.d/nodejs.sh

# Post to nomnom
curl \
  --data @$build_dir/package.json \
  --fail \
  --silent \
  --request POST \
  --header "content-type: application/json" \
  https://nomnom.heroku.com/?request_id=$REQUEST_ID \
  > /dev/null
