#!/usr/bin/env bash
# Generate docker-compose.extra.yml: one service per app in EXTRA_APPS.
# Regenerated on every up/rebuild, never committed.
#
# An extra app is not a special kind of app — it gets the same service as web,
# admin and landing. So the definition is not written out by hand here: the x-*
# anchor blocks are copied verbatim out of docker-compose.yml and reused.
source "$(dirname "${BASH_SOURCE[0]}")/common.sh"

OUT="${RUN_DIR}/docker-compose.extra.yml"
BASE="${PACKAGE_DIR}/docker-compose.yml"
mkdir -p "${RUN_DIR}"

if [ -z "$(extra_app_names)" ]; then
  rm -f "${OUT}"
  exit 0
fi

# Everything above `services:` except the project name: the anchors, as written.
anchor_blocks() {
  sed -n '/^x-/,$p' "${BASE}" | sed -n '/^services:/q;p'
}

{
  echo "# Generated by scripts/gen-apps.sh — do not edit."
  echo "# One service per EXTRA_APPS entry; edit run.config.json and re-run up."
  anchor_blocks
  echo "services:"

  # The shared install covers the built-in apps; EXTRA_DEPS_APPS is the hook
  # that adds these to it. Compose merges the one key over the anchor's map.
  echo "  frontend-deps:"
  echo "    environment:"
  echo "      <<: *frontend-env"
  echo "      EXTRA_DEPS_APPS: \"\${EXTRA_DEPS_APPS:-} $(extra_app_names | tr '\n' ' ')\""
  echo

  # The dashboard reads EXTRA_APPS and each port to draw its tiles.
  echo "  dashboard:"
  echo "    environment:"
  echo "      EXTRA_APPS: \"${EXTRA_APPS:-}\""
  mobile_extras=""
  while IFS= read -r name; do
    echo "      $(extra_app_key "${name}")_PORT: \"$(extra_app_port "${name}")\""
    extra_app_is_mobile "${name}" && mobile_extras="${mobile_extras}${mobile_extras:+ }${name}"
  done < <(extra_app_names)
  echo "      EXTRA_APPS_MOBILE: \"${mobile_extras}\""
  echo

  while IFS= read -r name; do
    port="$(extra_app_port "${name}")"
    key="$(extra_app_key "${name}")"
    if extra_app_is_mobile "${name}"; then
      # A second Metro, run exactly like mobile-client.
      cat <<EOF
  ${name}:
    <<: *frontend-service
    environment:
      <<: *frontend-env
      APP_CMD: \${${key}_CMD:-}
      MOBILE_APP: "${name}"
      MOBILE_STACK: \${${key}_STACK:-auto}
      EXPO_NO_TELEMETRY: "1"
      EXPO_DEVTOOLS_LISTEN_ADDRESS: 0.0.0.0
      REACT_NATIVE_PACKAGER_HOSTNAME: \${REACT_NATIVE_PACKAGER_HOSTNAME:-localhost}
      RCT_METRO_PORT: "${port}"
      EXPO_PUBLIC_API_BASE_URL: \${EXPO_PUBLIC_API_BASE_URL:-http://localhost:8000/api}
    command: ["metro", "${name}", "${port}"]
    ports:
      - "${port}:${port}"

EOF
    else
      cat <<EOF
  ${name}:
    <<: *frontend-service
    environment:
      <<: *frontend-env
      APP_CMD: \${${key}_CMD:-}
    command: ["app", "${name}", "${port}"]
    ports:
      - "${port}:${port}"

EOF
    fi
  done < <(extra_app_names)
} > "${OUT}"
