#!/usr/bin/env bash

####### Configure environment

set -o errexit    # always exit on error
set -o errtrace   # trap errors in functions as well
set -o pipefail   # don't ignore exit codes when piping output
set -o posix      # more strict failures in subshells
# 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

####### Determine current state

head "Reading application state"
read_current_state
show_current_state

if [ "$iojs_engine" == "" ]; then
  warn_node_engine "$node_engine"
else
  warn_node_engine "$iojs_engine"
fi
warn_node_modules "$modules_source"

####### Vendor in binaries

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

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

head "Building dependencies"
cd $build_dir
build_dependencies

####### 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
