#!/bin/bash

OWNER=$1
SERVICE=$2
BUCKET=${3:-"$OWNER-deploy"}

echo "Deploying Update..."
APPLICATION="deploy-$OWNER-$SERVICE-$ENVIRONMENT"
DEPLOY_CODE=$(aws deploy create-deployment --profile $ACCOUNT_ID --region us-west-2 --application-name $APPLICATION --deployment-group-name main --description "Jenkins DEPLOY $BUILD_NUMER of $GIT_COMMIT" --s3-location bucket=$BUCKET,bundleType=tgz,key=$OWNER/$SERVICE/$GIT_COMMIT.tgz --output text)

if [ $? -ne 0 ] ; then
    echo "Failed to create deployment."
    exit 1
fi

echo "Waiting for deployment status."
aws deploy wait deployment-successful --profile $ACCOUNT_ID --region us-west-2 --deployment-id $DEPLOY_CODE --output text

DEPLOY_SUCCESS=$?
if [ $DEPLOY_SUCCESS -eq 0 ] ; then
    echo "Successfully deployed $GIT_COMMIT as $DEPLOY_CODE"
else
    echo "Failed to deploy $GIT_COMMIT as $DEPLOY_CODE"
    aws deploy list-deployment-instances --profile $ACCOUNT_ID --region us-west-2 --deployment-id $DEPLOY_CODE --instance-status-filter FAILED --output text |
        awk '{ print $2 }' |
        while read instance; do aws deploy get-deployment-instance --profile $ACCOUNT_ID --region us-west-2 --deployment-id $DEPLOY_CODE --instance-id $instance --output json; done
fi
exit $DEPLOY_SUCCESS
