#!/bin/bash

if [ -f test_suite_exit_code.log ]; then
  TEST_SUITE_EXIT_CODE=`cat test_suite_exit_code.log`
fi

# Slack Notification Configuration
if [ -f resources/output/.tfci_sha ]; then
  # Automation Web Environment Creation
  if [ $TEST_SUITE_EXIT_CODE != "0" ]; then
    # Only send slack notification if exit code was a failure
    GITHUB_COMMIT=`cat resources/output/.tfci_sha`

    echo "[INFO] Will attempt to send slack notifications to $GITHUB_CREATOR for commit $GITHUB_COMMIT (PR scenario)"
    BUILD_NUMBER=$BUILD_NUMBER JOB_NAME=$JOB_NAME JENKINS_TOKEN=$JENKINS_KEY JENKINS_USERNAME=$JENKINS_USER \
      SLACK_TOKEN=$SLACK_KEY NOTIFICATIONS=$NOTIFICATIONS SLACK_USER_OVERRIDE=$GITHUB_CREATOR \
      ruby resources/scripts/notify_dev_script.rb
  else
    echo "[INFO] Build exit code ${TEST_SUITE_EXIT_CODE} was success. Not sending Slack notification."
  fi
else
  # Non Automation Web Environment Creation
  echo "[INFO] Will attempt to send slack notifications (non-PR scenario)"
  BUILD_NUMBER=$BUILD_NUMBER JOB_NAME=$JOB_NAME JENKINS_TOKEN=$JENKINS_KEY JENKINS_USERNAME=$JENKINS_USER \
    SLACK_TOKEN=$SLACK_KEY NOTIFICATIONS=$NOTIFICATIONS \
    ruby resources/scripts/notify_dev_script.rb
fi

# Web Environment PR Configuration: Commenting & Github Status Hook
if [[ -f resources/output/.tfci_pr && -f resources/output/.tfci_sha ]]; then
  SMOCA_URL="https://smoca.internal.justin.tv/job/${JOB_NAME}/${BUILD_NUMBER}"

  # Set status & message strings based on the exit code
  if [ $TEST_SUITE_EXIT_CODE == "0" ]; then
    status='success'
    hook_message="Build $BUILD_NUMBER was successful"
  elif [ $TEST_SUITE_EXIT_CODE == "1" ]; then
    status='failure'
    hook_message="Build $BUILD_NUMBER failed"
  else
    status='unknown'
    hook_message="Build $BUILD_NUMBER has an unknown status"
  fi

  # Report the Status To Github
  echo "[INFO] Reporting status ${status} to Github Notifier"
  GITHUB_OWNER=web
  GITHUB_REPO=web-client
  GITHUB_COMMIT=`cat resources/output/.tfci_sha`
  ./resources/scripts/github_commit_notifier.sh \
    -t $GITHUB_ACCESS_TOKEN \
    -c $GITHUB_COMMIT \
    -s $status \
    -d "$hook_message" \
    -u $SMOCA_URL \
    -f $JOB_NAME \
    -o $GITHUB_OWNER \
    -r $GITHUB_REPO

  # Post a comment on the PR
  staging_host="https://"${ENVIRONMENT/clean-/}"-www.dev.us-west2.twitch.tv"
    ./resources/scripts/github_pr_commenter.sh \
    -t $GITHUB_ACCESS_TOKEN \
    -o web \
    -r web-client \
    -c "Smoca Results: $status. \nBuild URL: ${SMOCA_URL} \nStaging Host URL: ${staging_host}" \
    -p $(cat resources/output/.tfci_pr)
fi
