#!/bin/bash

# This script iterates through all nodes in a Kubernetes cluster and, for each node,
# provides a detailed description and lists all the pods running on it.

# Set color codes for better readability
BLUE='\033[0;34m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

echo -e "${BLUE}Fetching list of all nodes in the cluster...${NC}"

# Get a list of all node names, skipping the header row.
# 'kubectl get nodes --no-headers' gets the node list without the header.
# 'awk '{print $1}'' prints only the first column (the node names).
NODE_LIST=$(kubectl get nodes --no-headers | awk '{print $1}')

# Check if any nodes were found to prevent errors.
if [ -z "$NODE_LIST" ]; then
  echo "Error: No nodes found in the cluster."
  exit 1
fi

echo -e "${GREEN}Found nodes. Starting inspection...${NC}"

# Loop through each node name in the list.
for node in $NODE_LIST; do
  # Print a clear separator for each node's output.
  echo -e "\n${BLUE}======================================================================${NC}"
  echo -e "${GREEN}Processing Node: $node${NC}"
  echo -e "${BLUE}======================================================================${NC}\n"

  echo -e "${GREEN}### Listing all pods on '$node'...${NC}"
  kubectl get pods --all-namespaces --field-selector spec.nodeName="$node"
  echo ""
done

echo -e "${BLUE}Script finished processing all nodes.${NC}"

