#!/usr/bin/env bash

BUILD_DIR=$1
CACHE_DIR=$2
BIN_DIR=$(cd $(dirname $0); pwd) # absolute path
NODE_VERSION="0.10.15"
NODE_URL="http://s3pository.heroku.com/node/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.gz"

source $BIN_DIR/common.sh

# Output debug info on exit
trap cat_npm_debug_log EXIT

status "Downloading node v$NODE_VERSION"
echo "$NODE_URL" | indent
tar_download $NODE_URL $BUILD_DIR

status "Moving node and npm to build directory"
mv $BUILD_DIR/node-v$NODE_VERSION-linux-x64 $BUILD_DIR/node

status "Making node and npm executable"
chmod +x $BUILD_DIR/node/bin/*

status "Adding node and npm to the \$PATH"
PATH=$PATH:$BUILD_DIR/node/bin

status "Installing dependencies with npm"
cd $BUILD_DIR
npm install --production | indent
echo "Dependencies installed" | indent

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