#!/bin/bash
set -e
source "$ROOT_PATH"/scripts/common.sh
echo_green "##################### NODE_MAX_MEM ##########################"

srv="$SVC_NAME"
env="$ENV_NAME"
maxmem="1536"

ECS_DEFAULT_REGION=$(python3 -c "import aws.constants; print(aws.constants.ECS_DEFAULT_REGION)")


for name in $(aws ecs describe-task-definition --task-definition $srv-family-$env --region $ECS_DEFAULT_REGION | jq -c ".taskDefinition.containerDefinitions[]" || handle_error "error in get task definition data")

do
  mem=$(echo $name | grep "name\":\"$srv-$env" | grep -oE "memory\":[0-9]+" | cut -d ":" -f2 || handle_error "error in filtering task defenition output")
  if [ $(echo $mem | wc -c) -gt 1 ]; then
    echo "the memory from task definision:"
    echo_green $mem
    maxmem="$(( mem - 512 ))"
  fi
  re='[0-9]+'
  if ! [[ $maxmem =~ $re ]] ; then
     maxmem="1536"
  fi
done

echo "APP_NODEJS_AVAIL_MEMORY=$maxmem" >> $GITHUB_ENV
echo "APP_NODE_OPTIONS=--max-old-space-size=$maxmem $EXTRA_NODE_OPTIONS" >> $GITHUB_ENV

echo_green "the max mem for nodejs is:"
echo_green $maxmem
