#!/usr/bin/env bash

set -e #Quit as soon as there is an error or exit

if [ "$TRAVIS" = "true" ] && [ "$TRAVIS_PULL_REQUEST" = "false" ]; then
    if [ -n "$USER_NAME" ]; then
      # inside this git repo we'll pretend to be a new user
      git config --global user.name "$USER_NAME"
      git config --global user.email "$USER_MAIL"
    fi

    if [ \( "$TRAVIS_BRANCH" = "patch" \) -o \( "$TRAVIS_BRANCH" = "minor" \) -o \( "$TRAVIS_BRANCH" = "major" \) ]; then
        gulp build --env production
        original_dir=`pwd`
        rm -rf /var/tmp/release
        mkdir -p /var/tmp/release
        cd /var/tmp/release
        git clone --branch RELEASE -q --single-branch --depth 1 "https://$GH_TOKEN@github.com/Verecom/videojs-vmap-vast-vpaid" .
        old_version=`cat bower.json | grep version | awk -F\" '{print $4}'`
        rsync -a --del --exclude=.git --exclude=.publish $original_dir/ ./
        gulp bump --version $old_version --type $TRAVIS_BRANCH
        git add -A .
        new_version=`cat bower.json | grep version | awk -F\" '{print $4}'`
        git commit -m "[RELEASE] build and release $new_version"
        git tag $new_version
        if git push && git push --tags ; then
            gulp deploy-demo
        else
            echo "Push failed probably due to concurrent trigger of release build"
        fi
        cd $original_dir
    fi
fi
