#!/usr/bin/env bash

git config --global user.email "tomster@emberjs.com"
git config --global user.name "Tomster"

# This specifies the repository we are going to work with.  This will most likely be set to 'ember'
COMPONENTS_EMBER_REPO_SLUG="components/ember-data"

# This specifies the user who is associated to the GH_TOKEN
USER="rwjblue"

# This ensure that no directories within dist will be copied when script is run.
INCLUDED_FILES=`find dist/globals -maxdepth 1 -type f`

CURRENT_BRANCH=$TRAVIS_BRANCH

echo -e "COMPONENTS_EMBER_REPO_SLUG: ${COMPONENTS_EMBER_REPO_SLUG}\n"
echo -e "INCLUDED_FILES: ${INCLUDED_FILES}\n"
echo -e "CURRENT_BRANCH: ${CURRENT_BRANCH}\n"

if [[ $TRAVIS_PULL_REQUEST != "false" ]]; then
  echo "not publishing because this is a pull request."
  exit 0
fi

if [[ -z $GH_TOKEN ]]; then
  echo "secure environment variables not detected."
  echo "not a repo owner, exiting."
  exit 0
fi

# Set channel to publish to.  If no suitable branch is found exit successfully.
case $CURRENT_BRANCH in
  "master" )
    CHANNEL="canary" ;;
  "beta" )
    CHANNEL="beta" ;;
  "stable"  )
    CHANNEL="release" ;;
  "release" )
    CHANNEL="release" ;;
  * )
    echo "Not a bower release branch.  Exiting!"
    exit 0 ;;
esac
echo -e "CHANNEL: ${CHANNEL}\n"

# sending output to /dev/null to prevent GH_TOKEN leak on error
git clone --branch ${CHANNEL} https://${USER}:${GH_TOKEN}@github.com/${COMPONENTS_EMBER_REPO_SLUG}.git bower_ember &> /dev/null
rm -rf bower_ember/*
cp -r ${INCLUDED_FILES} bower_ember/
cd bower_ember
git remote rm origin

# sending output to /dev/null to prevent GH_TOKEN leak on error
git remote add origin https://${USER}:${GH_TOKEN}@github.com/${COMPONENTS_EMBER_REPO_SLUG}.git &> /dev/null
git add -A
git commit -m "Ember Data Bower Auto build for https://github.com/emberjs/data/commits/${TRAVIS_COMMIT}."

# sending output to /dev/null to prevent GH_TOKEN leak on error
git push -fq origin ${CHANNEL} &> /dev/null
echo -e "Done\n"

