#!/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-stable-version"
#   assertCaptured "Node.js"
#   assertCapturedSuccess
# }

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

testPackageJsonWithoutVersion() {
  compile "package-json-noversion"
  assertCaptured "WARNING: No node version specified"
  assertCaptured "Using latest stable node"
  assertCapturedSuccess
}

testPackageJsonWithStableVersion() {
  compile "package-json-stable-version"
  assertNotCaptured "WARNING: No node version specified"
  assertCaptured "Using latest stable node"
  assertCapturedSuccess
}

testPackageJsonWithUnstableVersion() {
  compile "package-json-unstable-version"
  assertCaptured "Using node version 0.11"
  assertCapturedSuccess
}

# testPackageJsonWithInvalidVersion() {
#   compile "package-json-invalidversion"
#   assertCapturedError 1 "Requested node version 5.0 not found"
# }

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

testNodeModulesCached() {
  cache=$(mktmpdir)
  compile "node-modules-caching" $cache
  assertEquals "1" "$(ls -1 $cache/node_modules/0.10.18 | wc -l)"
}

## 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:-$(mktmpdir)}
}

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

source ${BASE}/vendor/shunit2/shunit2