#!/bin/bash
set -e

if [[ "$CI" != "true" ]]; then
  echo "(bailing: not in CI)"
  exit
elif [[ $# -lt 1 ]]; then
  echo "No status provided!" >&2
  exit 1
fi

# XXX this will go away if we build pushes instead of PRs
if [[ "$TRAVIS_PULL_REQUEST_SHA" != "" ]]; then
  # setting TRAVIS_COMMIT inline here is a fix for:
  # <https://github.com/taskworld/commit-status/issues/5>
  export TRAVIS_COMMIT=$TRAVIS_PULL_REQUEST_SHA
fi

_status=$1

version=$(jq -r .version package.json)
rubygems=$(jq -r .rubygems package.json)
npm=$(jq -r .name package.json)

if [ "$rubygems" != "null" ]; then
  name=$rubygems
  # the commit status context
  context="gem push $name"
  version=$(grep -oE '"([0-9\.a-z\-]+)"' lib/**/version.rb | sed -e 's/"//g')
  message="https://rubygems.org/gems/$name/versions/$version"
else
  name=$npm
  # the commit status context
  context="npm publish $name"
  message="https://unpkg.com/$name@$version/"
fi

echo "📡 Transmitting publish status for $context $name@$version..."
commit-status "$_status" "$context" "$name@$version" "$message"
