#!/bin/bash

# Usage: start-debug-pod.sh <pvc-name> <namespace>

# Validate input parameters
if [ $# -ne 2 ]; then
  echo "Usage: start-debug-pod.sh <pvc-name> <namespace>"
  exit 1
fi

PVC_NAME=$1
NAMESPACE=$2

if [ -z "$PVC_NAME" ] || [ -z "$NAMESPACE" ]; then
  echo "PVC name and namespace cannot be empty"
  exit 1
fi

# Check if namespace exists
if ! kubectl get namespace "$NAMESPACE" > /dev/null 2>&1; then
  echo "Namespace $NAMESPACE does not exist"
  exit 1
fi

# Check if PVC exists in the specified namespace
if ! kubectl get pvc "$PVC_NAME" -n "$NAMESPACE" > /dev/null 2>&1; then
  echo "PVC $PVC_NAME does not exist in namespace $NAMESPACE"
  exit 1
fi

# Define the name of the debug pod
DEBUG_POD_NAME="debug-pod-$PVC_NAME"

# Create the YAML file for the debug pod
kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
  name: $DEBUG_POD_NAME
  namespace: $NAMESPACE
spec:
  containers:
  - name: debug-container
    image: busybox
    imagePullPolicy: IfNotPresent
    command: ["/bin/sleep", "3600"]
    volumeMounts:
    - name: your-pvc
      mountPath: /mnt/data
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
  volumes:
  - name: your-pvc
    persistentVolumeClaim:
      claimName: $PVC_NAME
  terminationGracePeriodSeconds: 30
EOF

# Wait for the pod to be ready
kubectl wait --for=condition=Ready pod/$DEBUG_POD_NAME -n $NAMESPACE

# Open a shell inside the debug pod
kubectl exec -it $DEBUG_POD_NAME -n $NAMESPACE -- /bin/sh

trap 'kubectl delete pod $DEBUG_POD_NAME -n $NAMESPACE' EXIT
