#!/bin/bash
set -euo pipefail

post_pr_diff_to_github() {
  issue_id=$1
  pr_head_sha=$2
  url="https://$GITHUB_AUTH_TOKEN@api.github.com/repos/caciviclab/disclosure-backend-static/issues/${issue_id}/comments"
  cat <<BODY | jq -R -s '{ body: . }' | curl -v -H"Content-Type: application/json" -d@- "$url"
<details>
<summary>Build diff from Commit ${pr_head_sha}:</summary>

\`\`\`diff
$(git add -N . && git diff | head -c 64000)
\`\`\`
</details>
BODY

}

deploy() {
  set -x
  git add build
  git config --global user.name 'OpenDisclosure Deploybot'
  git config --global user.email 'open-disclosure@gmail.com'
  git commit -m 'Run `make clean download import process`

This is an automated update by travis-ci at
'"$(date)"'

[skip ci]'
  # Push to the same branch instead of master
  git push \
    "https://$GITHUB_AUTH_TOKEN@github.com/caciviclab/disclosure-backend-static.git" \
    HEAD:${TRAVIS_BRANCH} \
    | sed -e "s/$GITHUB_AUTH_TOKEN/[removed]/"

  if [ "${TRAVIS_BRANCH}" = "master" -a ! "${TRAVIS_EVENT_TYPE}" = "pull_request" ]; then
    # only upload cache if we're merging onto the main branch
    make upload-cache
  fi
}

if [ "${TRAVIS_EVENT_TYPE}" = "pull_request" ]; then
  post_pr_diff_to_github "$TRAVIS_PULL_REQUEST" "$TRAVIS_PULL_REQUEST_SHA"
elif [ ! -d "build" ]; then
  echo "The 'build' directory is missing. Bailing!"
elif git diff --exit-code --quiet; then
  echo "No changes to deploy!"
elif [ ! "${TRAVIS_EVENT_TYPE}" = "pull_request" ]; then
  echo "Deploying build on all branches when build directory changed and not pull request build"
  deploy
else
  echo "Not deploying build on pull requests"
fi
