#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"

trigger-scheduler-app-status() {
  declare desc="fetches the status for a given app"
  declare trigger="scheduler-app-status"
  declare DOKKU_SCHEDULER="$1" APP="$2"

  if [[ "$DOKKU_SCHEDULER" != "docker-local" ]]; then
    return
  fi

  local PROCS=0 RUNNING=""
  local APP_CIDS=$(get_app_container_ids "$APP")

  for CID in $APP_CIDS; do
    if (is_container_status "$CID" "Running"); then
      RUNNING+="0"
    else
      RUNNING+="1"
    fi
    PROCS=$((PROCS + 1))
  done

  if [[ "${#RUNNING}" -eq 0 ]] || [[ "${#RUNNING}" -ne 0 ]] && [[ "$RUNNING" != *"0"* ]]; then
    RUNNING="false"
  elif [[ "$RUNNING" != *"1"* ]] && [[ "${#RUNNING}" -ne 0 ]]; then
    RUNNING="true"
  else
    RUNNING="mixed"
  fi

  echo "$PROCS $RUNNING"
}

trigger-scheduler-app-status "$@"
