#!/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 "disk utilization: "
  df -h --type btrfs --type ext4 --type ext3 --type ext2 --type vfat --type iso9660 | sed "s/^/       /"
  dokku_log_info1 "disk inode utilization: "
  df -hi --type btrfs --type ext4 --type ext3 --type ext2 --type vfat --type iso9660 | 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 "herokuish version: "
  if [[ "$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)"
  if command -v "dokku-event-listener" &>/dev/null; then
    dokku_log_info1 "dokku-event-listener version: $(dokku-event-listener version)"
  else
    dokku_log_warn "dokku-event-listener binary is not available"
  fi
  if command -v "dokku-update" &>/dev/null; then
    dokku_log_info1 "dokku-update version: $(dokku-update version)"
  else
    dokku_log_warn "dokku-update binary is not available"
  fi
  dokku_log_info1 "docker-container-healthchecker version: $(docker-container-healthchecker version)"
  dokku_log_info1 "docker-image-labeler version: $(docker-image-labeler version)"
  dokku_log_info1 "git version: $(git --version)"
  dokku_log_info1 "lambda-builder version: $(lambda-builder version)"
  dokku_log_info1 "netrc version: $(netrc version)"
  if command -v "pack" &>/dev/null; then
    dokku_log_info1 "pack version: $(pack version)"
  else
    dokku_log_warn "pack binary is not available"
  fi
  dokku_log_info1 "plugn version: $(plugn version)"
  dokku_log_info1 "sigil version: $(sigil -v)"
  dokku_log_info1 "sshcommand version: $(sshcommand 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 "$@"
