#!/bin/bash
#
# broadcast_github_context.sh
# Using the github API write the status for a known context
# GitHub APIv3 Docs: https://developer.github.com/v3/repos/statuses/
#
# Note: Please run this script within a Bamboo context!
# Usage: ./broadcast_github_context.sh <status> <platform> <state_description>
#        E.g. ./broadcast_github_context.sh "pending" "emu" "Queued"
#
# @copyright Highly Confidential and Proprietary Zoox Information. Copyright (c) Zoox
#
# Author: trawat
# Date Created: September 15, 2020
#

# Prevent script from being run outside of a Bamboo context or mocked Bamboo environment
if [ "$bamboo_build_working_directory" = "" ]; then
    help_msg=`tail -n+7 broadcast_github_context.sh | head -3`
    echo "${help_msg//# }"
    exit 0
fi

# Convenience variables for Python virtualenv environment
virt="gsu_env"
zoox_pypi="https://pypi.zooxlabs.com/simple"
public_pypi="https://pypi.python.org/simple"

# Check for virtual environment
if [ ! -d $virt ]; then
    # Requires Python 3.6 and virtualenv to be installed somewhere on host OS
    virtualenv -p $(which python3) $virt --python=python3.6
fi

# Set command-line args
commit_status="$1"             # "pending" "error" "success" or "failure" are recognized by API
context="FWVAL SMOKE TEST $2"  # smoke test key. e.g. "emu", "tbc smoke", usually matches dir name
info_message="$3"              # Description. E.g. "Pending" or "Running" reflect state of tests

# If any other virtual environment is active, deactivate it (this isn't likely in CI/CD pipeline
# but it might be true if this script is running on someones local system. Just to be safe.
deactivate 2> /dev/null

# Activate virtual environment
. $virt/bin/activate

# Install the gitsmoke package
pip install gitsmoke --index-url $zoox_pypi --extra-index-url $public_pypi

# Send API request with designated parameters
gitsmoke -r "$commit_status" -s $bamboo_repository_revision_number -u $bamboo_buildResultsUrl \
    -c "$context" -d "$info_message"

# Print informative message to log
if [ "$?" -eq 0 ]; then
    echo "Successfully communicated status for $bamboo_buildResultsUrl"
else
    echo "Could not update GitHub status for this Bamboo job"
fi
