#!/bin/bash

# Enable strict mode for safety
set -euo pipefail
IFS=$'\n\t'

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

# --- Preconditions ---
: "${APP_HOME:?APP_HOME environment variable is not set}"
: "${PATH_FROM_REPO_ROOT_OF_PHP_SCRIPT_TO_RUN:?PHP script path not provided}"

if [[ "${Environment:-}" =~ ^(qa|prod)$ ]]; then
    if [[ -n "${ECS_AGENT_URI:-}" ]]; then
        log "Setting ECS task protection for 10 minutes"
        set +e
        curl -X PUT "${ECS_AGENT_URI}/task-protection/v1/state" \
            -H "Content-Type: application/json" \
            -d '{"ProtectionEnabled":true, "ExpiresInMinutes":10}'
        log "Current task protection: $(curl -s -X GET "${ECS_AGENT_URI}/task-protection/v1/state")"
        set -e
    else
        log "Warning: ECS_AGENT_URI not set — skipping task protection"
    fi
fi

# --- Execute PHP Script ---
SCRIPT_PATH="${APP_HOME}/${PATH_FROM_REPO_ROOT_OF_PHP_SCRIPT_TO_RUN}"

if [[ ! -f "$SCRIPT_PATH" ]]; then
  log "Error: PHP script not found at $SCRIPT_PATH"
  exit 1
fi

log "Executing PHP script: $SCRIPT_PATH"
php "$SCRIPT_PATH" 
log "Execution completed successfully"
