#!/usr/bin/env bash

#
# Create a Heroku app with the following buildpack:
# https://github.com/ddollar/buildpack-test
#
# Push this Node.js buildpack to that Heroku app to
# run the tests
#

testDetectWithPackageJson() {
  detect "package-json-version"
  assertCaptured "Node.js"
  assertCapturedSuccess
}

testDetectWithoutPackageJson() {
  detect "no-package-json"
  assertCapturedError 1 ""
}

testPackageJsonWithVersion() {
  compile "package-json-version"
  assertNotCaptured "WARNING: No version of Node.js specified"
  assertCaptured "Using Node.js version: 0.6.11"
  assertCaptured "Using npm version: 1.1.9"
  assertCapturedSuccess
}

testPackageJsonWithoutVersion() {
  compile "package-json-noversion"
  assertCaptured "WARNING: No version of Node.js specified"
  assertCaptured "Using Node.js version: 0.10"
  assertCaptured "Using npm version: 1.3"
  assertCapturedSuccess
}

testPackageJsonWithInvalidVersion() {
  compile "package-json-invalidversion"
  assertCapturedError 1 "Requested engine npm version 1.1.5 does not"
}

testNothingCached() {
  cache=$(mktmpdir)
  compile "package-json-version" $cache
  assertCapturedSuccess
  assertEquals "0" "$(ls -1 $cache | wc -l)"
}

testProfileCreated() {
  compile "package-json-version"
  assertCaptured "Building runtime environment"
  assertFile "export PATH=\"\$HOME/bin:\$HOME/node_modules/.bin:\$PATH\"" ".profile.d/nodejs.sh"
  assertCapturedSuccess
}

## utils ########################################

pushd $(dirname 0) >/dev/null
BASE=$(pwd)
popd >/dev/null

source ${BASE}/vendor/test-utils/test-utils

mktmpdir() {
  dir=$(mktemp -t testXXXXX)
  rm -rf $dir
  mkdir $dir
  echo $dir
}

detect() {
  capture ${BASE}/bin/detect ${BASE}/test/$1
}

COMPILE_DIR=""

compile() {
  COMPILE_DIR=$(mktmpdir)
  cp -r ${BASE}/test/$1/* ${COMPILE_DIR}/
  capture ${BASE}/bin/compile ${COMPILE_DIR} $2
}

assertFile() {
  assertEquals "$1" "$(cat ${COMPILE_DIR}/$2)"
}

source ${BASE}/vendor/shunit2/shunit2
