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

cmd-report() {
  declare desc="reports dokku vitals for troubleshooting"
  declare cmd="report"
  [[ "$1" == "$cmd" ]] && shift 1
  declare APP="$1"
  local ARCHITECTURE="$(dpkg --print-architecture 2>/dev/null || true)"

  if [[ "$APP" == "--format" ]]; then
    dokku_log_fail "--format flag not supported on global report"
  fi

  dokku_log_info1 "uname: $(uname -a)"
  dokku_log_info1 "memory: "
  free -m | sed "s/^/       /"
  dokku_log_info1 "docker version: "
  "$DOCKER_BIN" version | sed "s/^/       /"
  dokku_log_info1 "docker daemon info: "
  "$DOCKER_BIN" -D system info | sed "s/^/       /"
  dokku_log_info1 "git version: $(git --version)"
  dokku_log_info1 "sigil version: $(sigil -v)"
  dokku_log_info1 "herokuish version: "
  if [[ "$ARCHITECTURE" == "armhf" ]] || [[ "$ARCHITECTURE" == "arm64" ]]; then
    dokku_log_warn "herokuish not supported on $ARCHITECTURE architecture"
  elif verify_image "$DOKKU_IMAGE"; then
    "$DOCKER_BIN" container run $DOKKU_GLOBAL_RUN_ARGS --rm "$DOKKU_IMAGE" herokuish version | sed "s/^/       /"
  else
    dokku_log_warn "Herokuish image $DOKKU_IMAGE is not available"
  fi
  dokku_log_info1 "dokku version: $(dokku_version)"
  dokku_log_info1 "plugn version: $(plugn version)"
  dokku_log_info1 "dokku plugins: "
  plugn list | sed "s/^/       /"

  if [[ "$APP" == "--all" ]]; then
    for app in $(dokku_apps); do
      plugn trigger report "$app"
    done
  elif [[ -n "$APP" ]]; then
    plugn trigger report "$APP"
  fi
}

cmd-report "$@"
