#!/usr/bin/env bash
# Usage: cached-npm install
#
# After running `npm`, caches the `node_modules` directory to S3.
# On the next run, restores the cached directory before running `npm`.
# When `package.json` changes, the cache gets rebuilt.
#
# Requirements:
# - package.json
# - TRAVIS_REPO_SLUG
# - TRAVIS_NODE_VERSION
# - S3_BUILD_CACHE_BUCKET
# - script/s3-put
# - npm
# - curl
#
# Author: Mislav Marohnić

set -e

compute_md5() {
  local output="$(openssl md5)"
  echo "${output##* }"
}

download() {
  curl --tcp-nodelay -qsfL "$1" -o "$2"
}

script_dir=$(dirname "${BASH_SOURCE[0]}")
bundle_path="node_modules npm_cache"
cache_busting_hash="$(compute_md5 < package.json)"
cache_name="npm-${TRAVIS_NODE_VERSION}-${cache_busting_hash}.tgz"
fetch_url="https://${S3_BUILD_CACHE_BUCKET}.s3.amazonaws.com/${TRAVIS_REPO_SLUG}/${cache_name}"

if download "$fetch_url" "$cache_name"; then
  echo "Reusing cached bundle ${cache_name}"
  tar xzf "$cache_name"
fi

NPM_CONFIG_CACHE=./npm_cache npm "$@"

if [ ! -f "$cache_name" ]; then
  if [ -z "$S3_SECRET_ACCESS_KEY" ] || [ -z "$S3_ACCESS_KEY_ID" ]
  then
    echo "Enviroment variables not set. Exiting..."
    exit 0
  fi

  echo "Caching \`${bundle_path}' to S3"
  tar czf "$cache_name" $bundle_path
  $script_dir/s3-put "$cache_name" "${S3_BUILD_CACHE_BUCKET}:${TRAVIS_REPO_SLUG}/${cache_name}"
fi

# vim: filetype=sh
