#!/usr/bin/env bash
set -e

# Asserts that this build runs in the context of the Go version that appears
# first in build configuration.
latest_go_version() {
  local go_version="$(grep '^go:' -A1 .travis.yml | tail -1)"
  go_version="${go_version#* - }"
  go_version="${go_version%.x}"
  [ -n "$go_version" ] && [[ "$(go version)" == *" go${go_version}".* ]]
}

publish_documentation() {
  local doc_dir="site"
  local doc_branch="gh-pages"
  local remote_url="$(git config remote.origin.url)"

  git fetch origin "${doc_branch}:${doc_branch}"
  git worktree add "$doc_dir" "$doc_branch"
  pushd "$doc_dir"

  git rm hub*.html >/dev/null
  cp ../share/man/*/*.html .
  git add hub*.html
  GIT_COMMITTER_NAME='Travis CI' GIT_COMMITTER_EMAIL='travis@travis-ci.org' \
    GIT_AUTHOR_NAME='Mislav Marohnić' GIT_AUTHOR_EMAIL='mislav@github.com' \
    git commit -m "Update documentation for $TRAVIS_TAG"

  git push "https://${GITHUB_OAUTH}@${remote_url#https://}" HEAD

  popd
}

if [[ $TRAVIS_TAG == v* ]] && [ "$TRAVIS_OS_NAME" = "linux" ] && latest_go_version && [ -n "$GITHUB_OAUTH" ]; then
  version="${TRAVIS_TAG#v}"
  make man-pages
  script/cross-compile "$version" | \
    PATH="bin:$PATH" script/github-release hub "$version"

  publish_documentation
fi
