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

trigger-scheduler-docker-local-scheduler-logs() {
  declare desc="scheduler-docker-local scheduler-logs plugin trigger"
  declare trigger="scheduler-logs"
  declare DOKKU_SCHEDULER="$1" APP="$2" PROCESS_TYPE="$3" TAIL="$4" PRETTY_PRINT="$5" NUM="$6"
  local DOKKU_LOGS_ARGS=""

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

  if [[ "$TAIL" == "true" ]]; then
    DOKKU_LOGS_ARGS="--follow "
  fi

  local APP_ROOT="$DOKKU_ROOT/$APP"
  local COLORS=(36 33 32 35 31)
  if [[ -n "$PROCESS_TYPE" ]]; then
    local CONTAINERS=("$APP_ROOT/CONTAINER.$PROCESS_TYPE".*)
  else
    local CONTAINERS=("$APP_ROOT"/CONTAINER.*)
  fi
  [[ -z $(stat -t "${CONTAINERS[0]}" 2>/dev/null) ]] && exit 0

  local DOKKU_LOGS_ARGS+="--tail $NUM"
  ((MAX_INDEX = ${#CONTAINERS[*]} - 1)) || true
  for i in ${!CONTAINERS[*]}; do
    local DYNO=$(echo "${CONTAINERS[i]}" | sed -r 's/.*CONTAINER\.(.*)/\1/')
    local CID=$(<"${CONTAINERS[i]}")
    local COLOR=${COLORS[i % ${#COLORS[*]}]}
    if [[ $PRETTY_PRINT == "true" ]]; then
      local DOKKU_LOGS_CMD+="($DOCKER_BIN logs $DOKKU_LOGS_ARGS $CID 2>&1)"
    else
      local DOKKU_LOGS_PRETTY_PRINT_CMD="sed -u -r 's/^([^Z]+Z )/\x1b[${COLOR}m\1app[$DYNO]:\x1b[0m /gm'"
      local DOKKU_LOGS_CMD+="($DOCKER_BIN logs -t $DOKKU_LOGS_ARGS $CID 2>&1 | $DOKKU_LOGS_PRETTY_PRINT_CMD)"
    fi
    if [[ $i != "$MAX_INDEX" ]]; then
      local DOKKU_LOGS_CMD+="& "
    else
      local DOKKU_LOGS_CMD+="; "
    fi
  done
  bash -c "($DOKKU_LOGS_CMD)"
}

trigger-scheduler-docker-local-scheduler-logs "$@"
