#!/usr/bin/env bash -e

# Log function
function log {
  printf '[%s] [%s] %s\n' "${0##*/}" "$( date '+%Y-%m-%dT%H:%M:%S' )" "${@}"
}

# Add task scale-in protection
log 'Setting task protection'
RESPONSE=$(curl -sf -X PUT --retry 3 "${ECS_AGENT_URI}/task-protection/v1/state" -d '{"ProtectionEnabled":true, "ExpiresInMinutes":2880}')
FAILURE_REASON=$(jq -r ".failure.Reason | select (.!=null)" <<< "${RESPONSE}")

case $FAILURE_REASON in
  DEPLOYMENT_BLOCKED) log "Could not set task protection due to in-progress deployment. Exiting..." && exit 0;;
  TASK_STOPPING_OR_STOPPED) log "Could not set task protection because task is stopping. Exiting..." && exit 0;;
  "") log "Successfully set task protection";;
  *) log "Failed to set task protection. Reason: ${FAILURE_REASON}" && exit 1;;
esac

log 'running handler.py'
ddtrace-run python3 handler.py
