#!/usr/bin/env bash
# shellcheck disable=SC2162,SC2046,SC2002,SC2086
set -euo pipefail

#
# GovCMS Drush
#
# Trap drush commands so that failures can be caught and sent
# to configured email addresses for further investigation.
#

TO='govcms.devops@salsadigital.com.au'
FROM="drush-notifications@govcms.gov.au"

# Comma separated list of emails.
GOVCMS_DRUSH_RECIPIENTS=${GOVCMS_DRUSH_RECIPIENTS:-}
GOVCMS_DRUSH_NOTIFICATION_ENABLE=${GOVCMS_DRUSH_NOTIFICATION_ENABLE:-false}
LAGOON_PROJECT=${LAGOON_PROJECT:-'base project'}

# Slack
SLACK_URL='https://hooks.slack.com/services/'

TMP=$(mktemp)
COMMAND="drush $*"

echo "GovCMS Drush"

send_errors() {
  ERROR=$(<$TMP)
  SUBJECT="GovCMS Drush failure for $LAGOON_PROJECT $LAGOON_GIT_BRANCH"

  echo "[fail]: Command failed sending notifications."

  if [[ $GOVCMS_DRUSH_RECIPIENTS != "" ]]; then
    TO="$TO,$GOVCMS_DRUSH_RECIPIENTS"
  fi

  sendmail $TO <<EOF
Subject: $SUBJECT
From: $FROM

GovCMS Drush command failed to complete successfully.
Command: $COMMAND
Error:
$ERROR

Please contact your development partner or support for assistance.
EOF

  # Send Slack notification if token is set.
  if [ -n "${SLACK_TOKEN}" ]; then
    send_slack "$ERROR"
  fi
}

send_slack() {
  # Escape and truncate for JSON.
  local ERROR
  ERROR="$(jq -n --arg msg "\`\`\`$(echo $1 | cut -f1,2 -d'[')\`\`\`" '$msg')"
  TIMESTAMP=$(date +"%s")
  # Post payload.
  curl \
  -H "Content-type: application/json" \
  -X POST $SLACK_URL$SLACK_TOKEN \
  -d \
    '
    {
      "attachments":[{
        "pretext": "*GovCMS Drush command failed to complete successfully.*",
        "fields":[
          {
            "title":"Project",
            "value":"'"$LAGOON_PROJECT"'",
            "short":"true"
          },
          {
            "title":"Branch",
            "value":"'"$LAGOON_GIT_BRANCH"'",
            "short":"true"
          },
          {
            "title":"Command",
            "value":"`'"$COMMAND"'`",
          },
          {
            "title":"Error",
            "value":'"$ERROR"',
          }
        ],
        "color":"danger",
        "ts":"'"$TIMESTAMP"'"
      }]
    }
    '
}

if $COMMAND 2> >(tee $TMP); then
  echo "[success]: Command completed successfully"
  exit
fi

if [ "$GOVCMS_DRUSH_NOTIFICATION_ENABLE" != "true" ]; then
  echo "[fail]: Command failed, notifications not enabled. Skipping."
  exit 1
fi

send_errors
rm $TMP
exit 1
