#!/bin/bash

#
# - This script runs in jenkins, grabbing values out of the environment and crafting a
#   json blob from them, and then publishing it to an sns topic in prod.  That sns topic
#   is consumed by a lambda function that will take these values, use them to query jenkins
#   for information related to this build, and then publish a message to slack, and a log
#   message into an ELK stack.
#

set -o pipefail

BIN=$(dirname $BASH_SOURCE)
export PWD=$(pwd)

for f in `ls ${BIN}/modules/*.sh`; do
  source ${f}
done

set +u

utils::notnull "SNS_USER_AWS_ACCESS_KEY_ID" ${SNS_USER_AWS_ACCESS_KEY_ID}
utils::notnull "SNS_USER_AWS_SECRET_ACCESS_KEY" ${SNS_USER_AWS_SECRET_ACCESS_KEY}
utils::notnull "GIT_COMMIT" ${GIT_COMMIT}
utils::notnull "BUILD_URL" ${BUILD_URL}
utils::notnull "BUILD_CAUSE" ${BUILD_CAUSE}

#
# Examples of values:
# 22:26:21 BUILD_URL=https://jenkins.internal.justin.tv/job/gds-extensions-ExtensionsDynamoToES-lambda-build-and-deploy/185/
# 22:26:21 BUILD_CAUSE=MANUALTRIGGER
#

cat > sns_message.txt <<EOF
{
	"GIT_COMMIT": "${GIT_COMMIT}",
	"BUILD_URL": "${BUILD_URL}",
	"BUILD_CAUSE": "${BUILD_CAUSE}",
	"API_URL": "${BUILD_URL}/api/json?pretty=true"
}
EOF

#
# - we must replace the (potentially) pre-existing AWS_* values with those specific for the
#   publishing of this SNS message
#
AWS_DEFAULT_REGION=${AWS_REGION:-"us-west-2"}
AWS_ACCESS_KEY_ID=${SNS_USER_AWS_ACCESS_KEY_ID}
AWS_SECRET_ACCESS_KEY=${SNS_USER_AWS_SECRET_ACCESS_KEY}

export AWS_DEFAULT_REGION
export AWS_ACCESS_KEY_ID
export AWS_SECRET_ACCESS_KEY

utils::check "sns publish" \
	aws sns publish --subject "jenkins build notification" --topic-arn "arn:aws:sns:us-west-2:523543649671:operational_events" --message file://sns_message.txt
