#!/usr/bin/env bash

####### Configure environment

set -e            # fail fast
set -o pipefail   # don't ignore exit codes when piping output
# set -x          # enable debugging

# Configure directories
build_dir=$1
cache_dir=$2
env_dir=$3
bp_dir=$(cd $(dirname $0); cd ..; pwd)
heroku_dir=$build_dir/.heroku
mkdir -p $heroku_dir/node
warnings=$(mktemp)

# Load dependencies
source $bp_dir/lib/common.sh
source $bp_dir/lib/build.sh
source $bp_dir/lib/warnings.sh

# Avoid GIT_DIR leak from previous build steps
unset GIT_DIR

# Provide hook to deal with errors
trap build_failed ERR

# Load config vars into environment; set smart defaults
export_env_dir $env_dir
export NPM_CONFIG_PRODUCTION=${NPM_CONFIG_PRODUCTION:-true}
export NODE_MODULES_CACHE=${NODE_MODULES_CACHE:-true}

####### Determine current state

iojs_engine=$(read_json "$build_dir/package.json" ".engines.iojs")
node_engine=$(read_json "$build_dir/package.json" ".engines.node")
node_previous=$(file_contents "$cache_dir/node/node-version")
npm_engine=$(read_json "$build_dir/package.json" ".engines.npm")
npm_previous=$(file_contents "$cache_dir/node/npm-version")
start_method=$(get_start_method "$build_dir")
modules_source=$(get_modules_source "$build_dir")
modules_cached=$(get_modules_cached "$cache_dir")

show_current_state

warn_node_engine "$node_engine"
warn_node_modules "$modules_source"

####### Vendor in binaries

head "Installing binaries"
if [ "$iojs_engine" == "" ]; then
  install_node
else
  install_iojs
fi
node_engine=`node --version`
install_npm

####### Build the project's dependencies

head "Building dependencies"
cd $build_dir

if [ "$modules_source" == "" ]; then
  info "Skipping dependencies (no source for node_modules)"

elif [ "$modules_source" == "prebuilt" ]; then
  info "Rebuilding any native modules for this architecture"
  npm rebuild 2>&1 | indent
  info "Installing any new modules"
  npm install --quiet --userconfig $build_dir/.npmrc 2>&1 | indent

else
  cache_status=$(get_cache_status)

  if [ "$cache_status" == "valid" ]; then
    info "Restoring node modules from cache"
    cp -r $cache_dir/node/node_modules $build_dir/
    info "Pruning unused dependencies"
    npm prune 2>&1 | indent
    info "Installing any new modules"
    npm install --quiet --userconfig $build_dir/.npmrc 2>&1 | indent
  else
    info "$cache_status"
    info "Installing node modules"
    touch $build_dir/.npmrc
    npm install --quiet --userconfig $build_dir/.npmrc 2>&1 | indent
  fi

fi

####### Create a Procfile if possible

head "Checking startup method"
ensure_procfile "$start_method" "$build_dir"
warn_start "$start_method"

####### Finalize the build

head "Finalizing build"
write_profile
write_export
clean_npm
clean_cache
create_cache
build_succeeded
