#!/bin/bash
# Runs all apps in dev mode, with all dependencies being "watched" by Rush and rebuilt automatically as changes are
# made. Dev mode for each app will pick up on these dependency rebuilds to give a "hot reloading"-like experience
# for all code in the repository.
scriptDir=$(cd -P -- "$(dirname -- "$0")" && pwd -P)
cd $scriptDir

set -e
# Kills subprocesses on exit
trap "trap - SIGTERM && kill -- -$$ 2>/dev/null" SIGINT SIGTERM EXIT

if [ "${AUTO_RUN_GIMME_AWS_CREDS}" = "true" ]; then
  gimme-aws-creds
else
  echo "Not auto-running gimme-aws-creds. Set AUTO_RUN_GIMME_AWS_CREDS to true to enable this."
fi

rush update

# Note: assumes package name is "@org/[app-directory-name]"
appShortNames="$( \
  rush list --json \
  | grep "\"path\": \"apps/" \
  | awk -F '"' '{print $4}' \
  | awk -F '/' '{print $2}' \
)"

maxShortNameLength=0
buildCommand="rush build:watch"
while IFS= read -r shortName; do
  if [ -f "apps/${shortName}/webpack.config.js" ]; then
    packageName=$(grep \"name\": "apps/${shortName}/package.json" | awk '{ print $2 }' | sed 's/[,"]//g')
    buildCommand="${buildCommand} --to-except ${packageName}"
    shortNameLength=${#shortName}
    if [ $shortNameLength -gt $maxShortNameLength ]; then
      maxShortNameLength=$shortNameLength
    fi
  fi
done <<< "$appShortNames"
${buildCommand} &

set -a # automatically export all variables
source .env
set -o xtrace # print out variables as they are set
source dev.env
set +o xtrace
set +a

# ASNI escape codes: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
# Original ordering below matches docker compose colors as of v1.26.2 per:
#   https://github.com/docker/compose/blob/master/compose/cli/colors.py
declare -a colorCodes=("36" "33" "32" "35" "34" "36;1" "33;1" "32;1" "35;1" "34;1")
colorCount=${#colorCodes[@]}
colorIndex=0
while IFS= read -r shortName; do
  colorIndex=$(($colorIndex % $colorCount))
  colorCode=${colorCodes[$colorIndex]}
  colorStart="\033[${colorCode}m"
  colorEnd="\033[0m"
  colorIndex=$(($colorIndex + 1))

  cd "apps/$shortName"
  appTagPrefix="$(printf %-$(($maxShortNameLength))s "$shortName")  | "
  if [ -f "webpack.config.js" ]; then
    envName="$(echo "${shortName//[^[:alnum:]]/_}" | awk '{print toupper($0)}')"
    portName="${envName}_PORT"
    appPort=$(grep "^$portName=" ../../.env | awk -F '=' '{print $2}')
    (PORT=$appPort rushx start:no-watch | sed -e "s/^/`printf "${colorStart}${appTagPrefix}${colorEnd}"`/") &
  fi
  cd ../..
done <<< "$appShortNames"

wait
