#!/bin/bash -e

sleep 10 # SYS-24580: pause for 10 seconds to give fluent bit some extra time to start 

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

ADDITIONAL_SUBDIRECTORIES=('public/assets/artist' 'public/assets/release' 'public/tmp/upload/delivery' 'public/tmp' 'data/db/youtubeclaiming' 'public/tmp/dmsingestfailure' 'public/tmp/saved_reports')

# Create temporary directory required by ppl script.
mkdir -p /tmp/ppl/input

# APP_HOME is provided by the Dockerfile
for DIR in "${ADDITIONAL_SUBDIRECTORIES[@]}"; do
  if [ ! -d "${APP_HOME}/${DIR}" ]; then
    mkdir -p "${APP_HOME}/${DIR}"
  fi
done

# Retrieve configs if in QA or Prod
if [ "${Environment}" = 'qa' ] || [ "${Environment}" = 'prod' ]; then

  AWS_COMMAND='/usr/local/bin/aws'

  if [ -x "${AWS_COMMAND}" ]; then
    ${AWS_COMMAND} s3 cp --quiet --recursive s3://"${S3_CONFIG_LOCATION}"/configs/ "${APP_HOME}"/application/configs/
    ${AWS_COMMAND} s3 cp --quiet --recursive s3://"${S3_CONFIG_LOCATION}"/public/ "${APP_HOME}"/public/
    find "${APP_HOME}/application/configs/" -type f -exec chmod 640 {} \;
    find "${APP_HOME}/public/" -type f -name "*.inc" -exec chmod 640 {} \;

    # Add task scale-in protection
    log 'Setting task protection'

    # SYS-22458: short-term fix as only service-managed tasks can receive task protection
    set +e
    curl -X PUT "${ECS_AGENT_URI}/task-protection/v1/state" -d '{"ProtectionEnabled":true, "ExpiresInMinutes":10}'
    log "Current task protection: $(curl -X PUT "${ECS_AGENT_URI}"/task-protection/v1/state)"
    set -e
  else
    log 'awscli not found' && exit 1
  fi

else
  log "Environment is ${Environment}, so do not manipulate config files"
fi

# Don't leave system config files in dangerous places
rm -rf "${APP_HOME}/deploy"

if [ -n "${CUSTOM_SCRIPT_COMMAND}" ]; then
  log "Running custom command: ${CUSTOM_SCRIPT_COMMAND}"
  echo "${CUSTOM_SCRIPT_COMMAND}" > /tmp/custom_script.sh
  chmod +x /tmp/custom_script.sh
  exec /tmp/custom_script.sh
else
  php ${APP_HOME}/${PATH_FROM_REPO_ROOT_OF_PHP_SCRIPT_TO_RUN} ${SCRIPT_ARGUMENTS}
fi
