#!/bin/bash

setup_author() {
  git config --global user.email "travis@travis-ci.org"
  git config --global user.name "Travis CI"
}

commit_push() {
  if ! git checkout "${TRAVIS_BRANCH}"; then
    echo "Failed to checkout ${TRAVIS_BRANCH}"
    return 1
  fi

  if ! git add dist/*; then
    echo "Failed to add dist files"
    return 2
  fi

  if ! git commit -m"Travis CI update - ${TRAVIS_BUILD_NUMBER} [ci skip]"; then
    echo "Failed to commit (probably nothing to commit)"
    return 0
  fi

  remote="https://${GITHUB_TOKEN}@github.com/${TRAVIS_REPO_SLUG}"
  if ! git push "${remote}" "${TRAVIS_BRANCH}" > /dev/null 2>&1; then
    echo "Failed to push"
    return 4
  fi 
}

if [ "${TRAVIS_BRANCH}" == "master" ] && [ "${TRAVIS_PULL_REQUEST}" == "false" ]; then
  setup_author
  commit_push
fi
