#!/bin/bash
# This script is used for the Web Client ENV Automation
# Steps:
# 1) Sends a Comment on the PR
# 2) Web-Hook that Build is Starting
# 3) Stores name of who's PR in /build/resources/output/.github_creator so notifs can send postbuild

if [ "$JOB_NAME" != 'qa-smoca' ]; then
  echo "[INFO] Exiting Pre Notification Handler Script. Job Name ${JOB_NAME} is not qa-smoca"
  exit 0
fi

# Attempt to fetch PR information from Consul to use for PR notifications
# If there is no info found, this was not triggered as part of the PR env automation
# Fetch Consul key holding PR info
pr=''
staging_host="https://"${ENVIRONMENT/clean-/}"-www.dev.us-west2.twitch.tv"
key="$(curl -s "http://consul.internal.justin.tv/v1/kv/autotfci/service/web-client/environments/${ENVIRONMENT/clean-/}?keys&pretty" | sed -n 's/.*\(autotfci.*tfci_PR\).*$/\1/p' | head -n1)"

if [[ -n $key ]]; then
  pr="$(curl -s "http://consul.internal.justin.tv/v1/kv/${key}?raw" | sed 's:.*pulls/::g')"
fi

SMOCA_URL="https://smoca.internal.justin.tv/job/${JOB_NAME}/${BUILD_NUMBER}"

if [[ -z $pr ]]; then
  echo '[INFO] This build was not triggered as part of Github PR environment automation'
  exit 0
else
  echo "[INFO] This build was triggered as part of web-client PR #${pr}"
  # Save the PR number to be used later for post build notification
  echo "${pr}" > /build/resources/output/.tfci_pr
  ./resources/scripts/github_pr_commenter.sh \
    -t $GITHUB_ACCESS_TOKEN \
    -o web \
    -r web-client \
    -c "Starting smoca build: ${SMOCA_URL} \n Staging Host URL: ${staging_host}  " \
    -p $pr
fi

# Mark commit status as pending while Smoca runs. Commit SHA is saved into .tfci_sha.
# NOTE: For now, continue with the assumption that pull requests are always from web/web-client.
# TODO: Review this in the future when PRs from more repos can trigger Smoca.
if [ -f /build/resources/output/.tfci_pr ]; then
  GITHUB_OWNER=web
  GITHUB_REPO=web-client
  GITHUB_PR=`cat /build/resources/output/.tfci_pr`
  GITHUB_COMMIT=`curl -LSs -H "Authorization: token ${GITHUB_ACCESS_TOKEN}" https://git-aws.internal.justin.tv/api/v3/repos/${GITHUB_OWNER}/${GITHUB_REPO}/pulls/${GITHUB_PR} | jq-linux64 ".head.sha" | sed -e 's/^"//' -e 's/"$//'`
  echo $GITHUB_COMMIT > /build/resources/output/.tfci_sha
  ./resources/scripts/github_commit_notifier.sh \
    -t $GITHUB_ACCESS_TOKEN \
    -c $GITHUB_COMMIT \
    -s pending \
    -d "'Build #$BUILD_NUMBER pending'" \
    -u $SMOCA_URL \
    -f "${JOB_NAME}" \
    -o $GITHUB_OWNER \
    -r $GITHUB_REPO
fi

# Capture the author of the PR and store it in an environment variable $GITHUB_CREATOR
# Smoca can then use this to report notifications & Gnosis data
if [ -f /build/resources/output/.tfci_pr ]; then
  PR_NUMBER=`cat /build/resources/output/.tfci_pr`
  GITHUB_LDAP_DN=`curl -LSs -H "Authorization: token $GITHUB_ACCESS_TOKEN" \
    https://git-aws.internal.justin.tv/api/v3/repos/web/web-client/pulls/$PR_NUMBER | \
    jq-linux64 ".user.ldap_dn" | tr -d '"'`

  if [ "$GITHUB_LDAP_DN" != "null" ] && [ ! -z "$GITHUB_LDAP_DN" ]; then
    # If the github ldap DN is filled, search ldap for it
    echo "[INFO] Searching for LDAP DN: ${GITHUB_LDAP_DN}"

    LDAP_USER=`ldapsearch -h ldap-vip.internal.justin.tv -p 1389 -b "dc=justin,dc=tv" \
      -x -b "${GITHUB_LDAP_DN}" | grep "uid: .*" | sed 's/uid: //'`
      # Grep will pull out the uid from the response, which is like: "uid: dylan"
      # sed will remove the "uid: " portion, so it's just "dylan"

    if [ ! -z "$LDAP_USER" ]; then
      # ldap-search returned a user
      echo "[INFO] Returned LDAP User: ${LDAP_USER}"
      export GITHUB_CREATOR=$LDAP_USER # Set this as an environment variable for Smoca to pick up
      echo "export GITHUB_CREATOR=\"${GITHUB_CREATOR}\"" > ~/.bashrc
      echo $GITHUB_CREATOR > /build/resources/output/.github_creator
    else
      # ldap-search failed to return a user
      echo "[WARN] Unable to find LDAP User for LDAP DN ${GITHUB_LDAP_DN}, PR: ${GITHUB_COMMIT}"
    fi
  else
    # LDAP DN info was not filled.
    echo "[WARN] Unable to find Github LDAP Information for PR: ${GITHUB_COMMIT}"
  fi
fi
