#!/bin/bash
# Adapted from https://gist.github.com/domenic/ec8b0fc8ab45f39403dd.

set -e

function tests {
  npm run test
  exit 0
}

function build {
  npm run test
  npm run build
}

# For build commits, do nothing
if [ "$TRAVIS_COMMIT_MESSAGE" == "Automated Linux Build" ] || [ "$TRAVIS_COMMIT_MESSAGE" == "Linux Build" ] || [ "$TRAVIS_COMMIT_MESSAGE" == "Automated macOS Build" ] || [ "$TRAVIS_COMMIT_MESSAGE" == "macOS Build" ]  || [ "$TRAVIS_COMMIT_MESSAGE" == "Automated Windows Build" ] || [ "$TRAVIS_COMMIT_MESSAGE" == "Windows Build" ] ; then
  echo -e "\e[36m\e[1mIgnorning automated build."
  exit 0
fi

# For revert branches, do nothing
if [[ "$TRAVIS_BRANCH" == revert-* ]]; then
  echo -e "\e[36m\e[1mBuild triggered for reversion branch \"${TRAVIS_BRANCH}\" - doing nothing."
  exit 0
fi

# For PRs, only run tests
if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
  echo -e "\e[36m\e[1mBuild triggered for PR #${TRAVIS_PULL_REQUEST} to branch \"${TRAVIS_BRANCH}\" - only running tests."
  tests
fi

# Figure out the source of the build
if [ -n "$TRAVIS_TAG" ]; then
  echo -e "\e[36m\e[1mBuild triggered for tag \"${TRAVIS_TAG}\"."
  SOURCE=$TRAVIS_TAG
  SOURCE_TYPE="tag"
else
  echo -e "\e[36m\e[1mBuild triggered for branch \"${TRAVIS_BRANCH}\"."
  SOURCE=$TRAVIS_BRANCH
  SOURCE_TYPE="branch"
fi

# For Node != 7, only run tests
if [ "$TRAVIS_NODE_VERSION" != "7" ]; then
  echo -e "\e[36m\e[1mBuild triggered with Node v${TRAVIS_NODE_VERSION} - only running tests."
  tests
fi

# Build bindings
build

# Initialise some useful variables
REPO=`git config remote.origin.url`
SSH_REPO=${REPO/https:\/\/github.com\//git@github.com:}
SHA=`git rev-parse --verify HEAD`

# Fix ssh_askpass on macOS
if [ $TRAVIS_OS_NAME == "osx" ]; then
  echo "#!/bin/bash
exit 0" > $HOME/ssh_askpass
  chmod +x $HOME/ssh_askpass
  export SSH_ASKPASS="$HOME/ssh_askpass"
fi

# Add github to the list of known hosts
ssh-keyscan -H github.com >> ~/.ssh/known_hosts

# Decrypt and add the ssh key
ENCRYPTED_KEY_VAR="encrypted_${ENCRYPTION_LABEL}_key"
ENCRYPTED_IV_VAR="encrypted_${ENCRYPTION_LABEL}_iv"
ENCRYPTED_KEY=${!ENCRYPTED_KEY_VAR}
ENCRYPTED_IV=${!ENCRYPTED_IV_VAR}
openssl aes-256-cbc -K $ENCRYPTED_KEY -iv $ENCRYPTED_IV -in deploy/deploy-key.enc -out deploy-key -d
chmod 600 deploy-key
eval `ssh-agent -s`
ssh-add deploy-key

# Commit and push
git checkout $TRAVIS_BRANCH
git pull $SSH_REPO $TRAVIS_BRANCH
git add -f bindings
git config user.name "Travis CI"
git config user.email "$COMMIT_AUTHOR_EMAIL"
if [ $TRAVIS_OS_NAME == "linux" ]; then
  if [ $TRAVIS_EVENT_TYPE == "cron" ]; then
    git commit -m "Automated Linux Build" || true
  else
    git commit -m "Linux Build" || true
  fi
elif [ $TRAVIS_OS_NAME == "osx" ]; then
  if [ $TRAVIS_EVENT_TYPE == "cron" ]; then
    git commit -m "Automated macOS Build" || true
  else
    git commit -m "macOS Build" || true
  fi
fi
git push $SSH_REPO $TARGET_BRANCH