#!/bin/bash
# github_status_upload.sh: Upload result of a Bamboo or other CI job to GitHub Status API
# @copyright Highly Confidential and Proprietary Zoox Information. Copyright (c) Zoox.
#
# Date Created: August 19, 2019
# Author: trawat
#
# Note: Please run this script within a Bamboo context!
#
# This script supports one of two modes upon execution...
#    Sentinel Usage: github_status_upload.sh            <-- create sentinel file
#    Upload Usage:   github_status_upload.sh "Context"  <-- upload result to github pull request for
#                                     context "Context". E.g. github_status_upload.sh "FW EMU Smoke"

# This script can also be used to create a 'sentinel' file that can be checked during
# subsequent steps within the same stage, for example, and if that file is present
# the script beyond this knows that the tests passed
# See http://bamboo.zooxlabs.com/chain/admin/config/defaultStages.action?buildKey=FWVAL-ES
# for additional details
if [ "$bamboo_build_working_directory" = "" ]; then
    help_msg=`tail -n+8 github_status_upload.sh | head -3`
    echo "${help_msg//# }"
    exit 0
fi

# (Step 1)
# The sentinel file is actually created by a different script present in the directory of
# each type of smoke test. If it has not been renamed it is called "create_bamboo_sentinel_file.sh"

# Convenience var for Python virtual 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 to be installed somewhere on host OS
    virtualenv -p $(which python3) $virt --python=python3.6
fi

# 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 someone's local system. Just to be safe.
deactivate 2> /dev/null

# Activate virtual environment
. $virt/bin/activate

# Install gitsmoke package (force re-install)
pip install gitsmoke --index-url $zoox_pypi --extra-index-url $public_pypi

# (step 2)
# The variables with "fwval_smoke_test" as part of their name are set by the Bamboo tasks within
# each Stage (each stage representing one smoke test). The variables are populated with either PASS
# or FAIL and we can inspect them here since the stages are set up to propagate the variables as
# Bamboo "Result" variables
test_count=0
pass_count=0
bamboo_variables=`printenv | sed 's;=.*;;'`
for smoke_test in $bamboo_variables; do
    if [ ! -z `echo $smoke_test | grep FWVAL_SMOKE_TEST` ]; then
        # convert 'bamboo_FWVAL_SMOKE_TEST_emu' to 'FWVAL_SMOKE_TEST_emu'
        strip_bamboo=$(echo $smoke_test | sed "s/bamboo_//")
        # convert 'FWVAL_SMOKE_TEST_emu' to 'FWVAL SMOKE TEST emu'
        context="$(echo $strip_bamboo | sed "s/_/ /g")"
        eval "test_result=\$$smoke_test"
        if [ "${test_result}" = "PASS" ]; then
            gitsmoke -r "success" -s $bamboo_repository_revision_number -u $bamboo_buildResultsUrl -c \
                "$context" -d "Passed on Build #$bamboo_buildNumber"
            pass_count=$((pass_count+1))
        else
            gitsmoke -r "failure" -s $bamboo_repository_revision_number -u $bamboo_buildResultsUrl -c \
                "$context" -d "Failed on Build #$bamboo_buildNumber"
        fi
        test_count=$((test_count+1))
    fi
done

# Has Minimum Sha default value if not set
if [ ! -v bamboo_FWVAL_PREREQ_HAS_MINIMUM_SHA ]; then
    # Consider branch as having minimum sha, TODO change to 0 once we pass through this transition period
    bamboo_FWVAL_PREREQ_HAS_MINIMUM_SHA=1
    echo "Setting default value for bamboo_FWVAL_PREREQ_HAS_MINIMUM_SHA=$bamboo_FWVAL_PREREQ_HAS_MINIMUM_SHA"
fi

# Construct and post overall github status
set -x
status_state="failure"
status_description="$pass_count/$test_count smoke tests passed"
if [ $pass_count -eq $test_count -a $test_count -gt 0 ]; then
    status_state="success"
elif [ ${bamboo_FWVAL_PREREQ_HAS_MINIMUM_SHA} -eq 0 ]; then
    # Note:
    # bamboo.FWVAL_PREREQ.HAS_MINIMUM_SHA
    #    is an injected bamboo variable from the "Has Minimum Revision" job
    # bamboo.FW_MIN_GIT_SHA
    #    is a bamboo plan variable from the "Firmware Test Global" plan.
    status_description="Missing minimum git sha=${bamboo_FW_MIN_GIT_SHA}; mandatory rebase is required."
fi
gitsmoke --result $status_state \
         --sha $bamboo_repository_revision_number \
         --url $bamboo_buildResultsUrl \
         --context "Firmware Smoke Tests" \
         --description "$status_description"
set +x

echo "Tests Run: ${test_count}, Tests Passed: ${pass_count}"
