#!/usr/bin/env bash

set -e

NAMESPACE="$(kubectl config view --minify --output 'jsonpath={..namespace}')"
NAMESPACE=${NAMESPACE:-default}
LABEL=""
ALL_NAMESPACES=false

print_usage() {
  echo "kube-all - A better 'kubectl get all' - actually get all Kubernetes resources, including custom resources"
  echo " "
  echo "kube-all [options]"
  echo " "
  echo "Options:"
  echo "-h, --help            show this help text"
  echo "-n, --namespace       the namespace the to search in"
  echo "-l, --selector        the label selector to match on"
  echo "-A, --all-namespaces  match resources in all namespaces (default: false)"
}

while test $# -gt 0; do
  case "$1" in
    -n|--namespace)
      shift
      NAMESPACE=$1
      shift
      ;;
    -l|--selector)
      shift
      LABEL=$1
      shift
      ;;
    -A|--all-namespaces)
      ALL_NAMESPACES=true
      shift
      ;;
    -h|--help)
      print_usage
      exit 0
      ;;
    *)
      break
      ;;
  esac
done

if [[ "${LABEL}" != "" ]]; then
  LABEL="-l ${LABEL}"
fi

NAMES="$(kubectl api-resources --namespaced --verbs list -o name | tr '\n' ,)"

if [[ "$ALL_NAMESPACES" == "true" ]]; then
  kubectl get "${NAMES::${#NAMES}-1}" --show-kind --ignore-not-found ${LABEL} -A
else
  kubectl get "${NAMES::${#NAMES}-1}" --show-kind --ignore-not-found ${LABEL} -n ${NAMESPACE}
fi