#!/bin/bash

# Set backup directory
BACKUP_DIR="k8s-backup-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BACKUP_DIR"

# Get all namespaces
kubectl get ns --no-headers | awk '{print $1}' | while read namespace; do
  # Create namespace directory
  NS_DIR="$BACKUP_DIR/$namespace"
  mkdir -p "$NS_DIR"

  # Get all resource types in this namespace
  kubectl api-resources --verbs=list --namespaced -o name | while read resource; do
    # Skip some internal resources
    if [[ $resource != "events"* ]] && [[ $resource != "events.events.k8s.io" ]]; then
      echo "Backing up $resource in $namespace"
      # Get all resources of this type and save to yaml
      kubectl get "$resource" -n "$namespace" -o yaml > "$NS_DIR/$resource.yaml" 2>/dev/null
    fi
  done
done

# Backup cluster-wide resources
CLUSTER_DIR="$BACKUP_DIR/cluster-resources"
mkdir -p "$CLUSTER_DIR"

# Get all non-namespaced resources
kubectl api-resources --verbs=list --namespaced=false -o name | while read resource; do
  echo "Backing up cluster resource $resource"
  kubectl get "$resource" -o yaml > "$CLUSTER_DIR/$resource.yaml" 2>/dev/null
done

# Create a tarball
tar -czf "$BACKUP_DIR.tar.gz" "$BACKUP_DIR"
rm -rf "$BACKUP_DIR"

echo "Backup completed: $BACKUP_DIR.tar.gz"
