#!/bin/bash
set -e

usage() {
    echo 'Usage: ./github_commit_notifier.sh -r <REPO> -o <OWNER> -t <GITHUB_ACCESS_TOKEN> -c <GIT_COMMIT> -s <STATUS> -d <DESCRIPTION> -u <BUILD URL> -f <TITLE>' 1>&2
    exit 1
}

while getopts ":t:c:s:d:u:f:r:o:" i; do
  case "${i}" in
    t)
        GH_ACCESS_TOKEN=${OPTARG}
        ;;
    c)
        GH_COMMIT=${OPTARG}
        ;;
    s)
        STATUS=${OPTARG}
        ;;
    d)
        DESCRIPTION=${OPTARG}
        ;;
    u)
        URL=${OPTARG}
        ;;
    f)
        TITLE=${OPTARG}
        ;;
    r)
        REPO=${OPTARG}
        ;;
    o)
        OWNER=${OPTARG}
        ;;
    *)
        usage
        ;;
  esac
done

shift $((OPTIND-1))

if [ -z "$GH_ACCESS_TOKEN" ] || [ -z "$GH_COMMIT" ] || [ -z "$STATUS" ] || [ -z "$OWNER" ] || [ -z "$REPO" ]; then
    usage
fi

curl "https://git-aws.internal.justin.tv/api/v3/repos/$OWNER/$REPO/statuses/$GH_COMMIT?access_token=$GH_ACCESS_TOKEN" \
    -H "Content-Type: application/json" \
    -X "POST" \
    -k \
    -d "{\"state\": \"$STATUS\", \"context\": \"$TITLE\", \"description\": \"$DESCRIPTION\", \"target_url\": \"$URL\"}"
