#!/usr/bin/env bash

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)

# Load some convenience functions like status() and indent()
source $bp_dir/bin/common.sh

# Expose user-installed bower
export PATH=$build_dir/node_modules/.bin:$PATH

# Get bower version
bower_bin=$(which bower)
bower_version=$(bower --version)
status "Using Bower $bower_version from ${bower_bin#$build_dir/}"

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

# Figure out where Bower should install the components
bower_install=$(node -pe 'JSON.parse(require("fs").readFileSync(process.argv[1])).directory || "bower_components"' .bowerrc)

# If the bower installation directory is checked into source control
# then assume that we are not supposed to touch it. Otherwise, restore
# from the build cache.
if test -d $build_dir/$bower_install; then
  status "Found existing $bower_install directory; skipping cache"
elif test -d $cache_dir/bower/install; then
  status "Restoring $bower_install directory from cache"
  cp -r $cache_dir/bower/install $build_dir/$bower_install

  status "Pruning cached dependencies not specified in bower.json"
  bower --allow-root --config.cwd=$build_dir prune 2>&1 | indent
fi

status "Installing bower dependencies"
bower --allow-root --config.cwd=$build_dir --config.storage.packages=$cache_dir/bower/packages --config.storage.registry=$cache_dir/bower/registry install 2>&1 | indent

# Purge bower-related cached content, being careful not to purge the top-level
# cache, for the sake of heroku-buildpack-multi apps.
rm -rf $cache_dir/bower
mkdir -p $cache_dir/bower

# If app has a node_modules directory, cache it.
if test -d $build_dir/$bower_install; then
  status "Caching $bower_install directory for future builds"
  cp -r $build_dir/$bower_install $cache_dir/bower/install/
fi
