#!/bin/sh

if [ "${TRAVIS_PULL_REQUEST}" != "false" ]; then
  echo "This is a PR, skip deploy."
  exit 0
fi

echo "DEBUG ENV: ${TRAVIS_JOB_NUMBER} ${TRAVIS_BUILD_NUMBER} ..."

if [ "${TRAVIS_BUILD_NUMBER}.4" != "${TRAVIS_JOB_NUMBER}" ]; then
  echo "Only run sauce labs 1 time 1 commit... quit."
  exit 0
fi

if [ "${TRAVIS_REPO_SLUG}" != "zordius/json-path-processor" ]; then
  echo "Skip deploy because this is a fork... quit."
  exit 0
fi

# push coverage to codeclimate
npm install codeclimate-test-reporter
npm run-script coverage
node_modules/.bin/codeclimate-test-reporter < coverage/lcov.info

# build JS files for dist and test
npm install badge-render browserify uglify-js karma karma-mocha karma-sauce-launcher karma-browserify watchify
npm run lint && npm run build_std && npm run build_dbg && npm run build_min && npm run build_tst

CODE=$?
if [ $CODE -ne 0 ]; then
  echo Build failed, abort.
  exit 1
fi

# do sauce labs tests
node_modules/.bin/karma start || exit $?

# Setup git
git config --global user.name "Travis-CI"
git config --global user.email "zordius@yahoo-inc.com"

git add dist
git commit -m "Auto build dist files for ${TRAVIS_COMMIT} [ci skip]"

node_modules/.bin/badge-saucelabs-results > badge.json
cat badge.json
node_modules/.bin/badge-render badge.json badge.html --png badge.png --scale 0.7 -width 490 -height 60
git add badge.png
git commit -m "Auto commit browser badge for ${TRAVIS_COMMIT} [ci skip]"

# push back dist files
git push "https://${GHTK}@github.com/zordius/json-path-processor.git" HEAD:${TRAVIS_BRANCH} > /dev/null 2>&1
