#!/usr/bin/env bash

# Get previous deployed commit for `master`
LAST_DEPLOYMENT_DATA=$(curl "https://clean-deploy.internal.justin.tv/v1/artifact/compare?env=clean-production&name=web-client&owner=web&ref=$GIT_COMMIT");
REGEXP='"previous_sha":"([^"]+)"'
if [[ $LAST_DEPLOYMENT_DATA =~ $REGEXP ]]
then
  CODE_REVIEW_URL="https://git-aws.internal.justin.tv/web/web-client/compare/${BASH_REMATCH[1]}...$GIT_COMMIT";
else
  echo "Can not find previously deployed SHA for $AUTO_DEPLOY_ENV. Code review URL will only include the deploying commit.";
  CODE_REVIEW_URL="https://git-aws.internal.justin.tv/web/web-client/commit/$GIT_COMMIT";
fi

COMMITTER_EMAIL=`git show ${GIT_COMMIT} --format='%ce' --no-patch`;
COMMIT_SUBJECT=`git show ${GIT_COMMIT} --format='%s' --no-patch`;
if [[ "$COMMIT_SUBJECT" =~ "Merge pull request"* ]]
then
  COMMIT_TITLE=`git show ${GIT_COMMIT} --format='<%an> %b' --no-patch`;
else
  COMMIT_TITLE=`git show ${GIT_COMMIT} --format='<%an> %s %b' --no-patch`;
fi

# Trigger a deployment via posting to the Skadi deployments endpoint. This is the same mechanism
# as is used by the deploy tool.
curl "https://clean-deploy.internal.justin.tv/v1/deployments" \
     -H "GithubAccessToken: $GITHUB_ACCESS_TOKEN" \
     --data-urlencode "description=$COMMIT_TITLE" \
     --data-urlencode "owner=web" \
     --data-urlencode "repo=web-client" \
     --data-urlencode "ref=$GIT_COMMIT" \
     --data-urlencode "branch=master" \
     --data-urlencode "environment=$AUTO_DEPLOY_ENV" \
     --data-urlencode "codeReviewURL=$CODE_REVIEW_URL" \
     --data-urlencode "severity=auto-deploy" \
     --data-urlencode "triggerSmoca=true" \
     --data-urlencode "creator=$COMMITER_EMAIL"
