#!/bin/bash

function ks {
  NAMESPACES="`mktemp`"
  kubectl get namespaces --output=json \
    | jq -r .items[].metadata.name \
    | grep -v "^kube-system$" \
    | grep -v "^kube-public$" \
    | grep -v "^kube-node-lease$" \
    > "$NAMESPACES"
  for NAMESPACE in $(cat "$NAMESPACES"); do
    DEPLOYMENTS="`mktemp`"
    DEPLOYMENT_PODS="`mktemp`"
    kubectl -n "$NAMESPACE" get deployments --output=json \
      | jq -r .items[].metadata.name \
      > "$DEPLOYMENTS"
    for DEPLOYMENT in $(cat "$DEPLOYMENTS"); do
      PODS="`mktemp`"
      kubectl -n "$NAMESPACE" --selector "app=$DEPLOYMENT" get pods --output=json \
        | jq -r .items[].metadata.name \
        > "$PODS"
      cat "$PODS" >> "$DEPLOYMENT_PODS"
      for POD in $(cat "$PODS"); do
        STATUS="`kubectl -n "$NAMESPACE" --selector="app=$DEPLOYMENT" get pods --output=json | jq -r ".items[] | select(.metadata.name==\\\"$POD\\\") | .status.phase"`"
        echo -e "$NAMESPACE\t$DEPLOYMENT\t$POD\t$STATUS"
      done
      rm "$PODS"
      done
    PODS="`mktemp`"
    kubectl -n "$NAMESPACE" get pods --output=json \
      | jq -r .items[].metadata.name \
      | grep -v -f "$DEPLOYMENT_PODS" \
      > "$PODS"
    for POD in $(cat "$PODS"); do
      STATUS="`kubectl -n "$NAMESPACE" get pods --output=json | jq -r ".items[] | select(.metadata.name==\\\"$POD\\\") | .status.phase"`"
      echo -e "$NAMESPACE\t_\t$POD\t$STATUS"
    done
    rm "$PODS"
    rm "$DEPLOYMENT_PODS"
    rm "$DEPLOYMENTS"
  done
  rm "$NAMESPACES"
}

ks | column -t | sort
