#!/bin/bash

# Configuration
DV_NAME="cirros-import-test"
NAMESPACE="default"
STORAGE_CLASS="ocs-storagecluster-ceph-rbd-virtualization"
REQUESTED_SIZE="1Gi"
TIMEOUT_SECONDS=300
SLEEP_INTERVAL=1
IMPORT_URL="https://download.cirros-cloud.net/0.4.0/cirros-0.4.0-x86_64-disk.img"

# --- DataVolume Definition (using a Here-Document) ---
DV_YAML=$(cat <<EOF
apiVersion: cdi.kubevirt.io/v1beta1
kind: DataVolume
metadata:
  name: ${DV_NAME}
  namespace: ${NAMESPACE}
spec:
  source:
    http:
      url: ${IMPORT_URL}
  storage:
    storageClassName: ${STORAGE_CLASS}
    accessModes:
      - ReadWriteOnce
    resources:
      requests:
        storage: ${REQUESTED_SIZE}
EOF
)

# Function to safely check command existence
command_exists () {
  command -v "$1" >/dev/null 2>&1
}

# Pre-flight checks
if ! command_exists oc; then
    echo "Error: oc command not found. Please ensure Kubernetes tools are installed and in your PATH." >&2
    exit 1
fi
if ! command_exists jq; then
    echo "Error: jq command not found. Please install jq (used for JSON parsing)." >&2
    exit 1
fi

echo "--- CDI DataVolume Import Checker (Loop Mode) ---"
echo "DataVolume Name: ${DV_NAME}"
echo "Import URL: ${IMPORT_URL}"
echo "Requested Size: ${REQUESTED_SIZE} | Storage Class: ${STORAGE_CLASS}"
echo "Timeout: ${TIMEOUT_SECONDS} seconds"
echo "Will loop forever until FAILURE BREAK is reproduced..."
echo ""

iteration=0

# Main loop - runs forever until FAILURE BREAK is found
while true; do
    iteration=$((iteration + 1))
    echo "=========================================="
    echo "🔄 Iteration #${iteration}"
    echo "=========================================="
    
    # 1. Create the DataVolume
    echo "Creating DataVolume: ${DV_NAME} in namespace ${NAMESPACE}..."
    echo "${DV_YAML}" | oc apply -f -

    if [ $? -ne 0 ]; then
        echo "Error: Failed to create DataVolume. Cleaning up and retrying..." >&2
        oc delete dv "${DV_NAME}" -n "${NAMESPACE}" --wait=false 2>/dev/null
        sleep 2
        continue
    fi

    # 2. Wait for underlying PVC to be Bound
    start_time=$(date +%s)
    elapsed_time=0
    CAPACITY=""
    
    echo "Waiting for DataVolume to create PVC and bind..."
    while [ ${elapsed_time} -lt ${TIMEOUT_SECONDS} ]; do
        # Check if PVC exists (DataVolume creates a PVC with the same name)
        PVC_EXISTS=$(oc get pvc "${DV_NAME}" -n "${NAMESPACE}" 2>/dev/null)
        
        if [ -n "$PVC_EXISTS" ]; then
            CAPACITY=$(oc get pvc "${DV_NAME}" -n "${NAMESPACE}" -o json | jq -r '.status.capacity.storage')
            PVC_PHASE=$(oc get pvc "${DV_NAME}" -n "${NAMESPACE}" -o jsonpath='{.status.phase}' 2>/dev/null)
            DV_PHASE=$(oc get dv "${DV_NAME}" -n "${NAMESPACE}" -o jsonpath='{.status.phase}' 2>/dev/null)

            if [ "$PVC_PHASE" == "Bound" ]; then
                echo "✅ PVC is Bound. DataVolume Phase: ${DV_PHASE}"
                break
            elif [ "$PVC_PHASE" == "Pending" ]; then
                echo "⏳ PVC Status: Pending, DV Status: ${DV_PHASE}... Waiting for provisioning."
            else
                echo "⚠️ PVC Status: ${PVC_PHASE}, DV Status: ${DV_PHASE}. Continuing to wait."
            fi
        else
            echo "⏳ Waiting for DataVolume to create PVC..."
        fi

        # sleep ${SLEEP_INTERVAL}
        elapsed_time=$(( $(date +%s) - start_time ))
    done

    # 3. Handle Timeout
    if [ "$PVC_PHASE" != "Bound" ]; then
        echo "❌ Timeout reached (${TIMEOUT_SECONDS}s). PVC did not become Bound. Current Phase: ${PVC_PHASE}." >&2
        echo "Cleaning up DataVolume and retrying..."
        oc delete dv "${DV_NAME}" -n "${NAMESPACE}" --wait=false
        sleep 2
        continue
    fi

    # 4. Check Capacity Field
    echo "Checking PVC capacity for successful provisioning..."

    # Capacity was already extracted in the loop above
    # Check if capacity is valid (not empty and not "null")
    if [[ -n "$CAPACITY" && "$CAPACITY" != "null" ]]; then
        echo "✅ PVC is Bound and Capacity is verified: ${CAPACITY}"
        echo "Cleaning up DataVolume for next iteration..."
        oc delete dv "${DV_NAME}" -n "${NAMESPACE}" --wait=false
        sleep 2
        continue
    else
        # This is the specific failure condition requested by the user
        echo ""
        echo "=========================================="
        echo "🛑 FAILURE BREAK REPRODUCED! 🛑"
        echo "=========================================="
        echo "After ${iteration} iterations, found PVC that is Bound but 'status.capacity.storage' field is empty, missing, or null."
        echo "Current capacity value: '${CAPACITY}'"
        echo "This indicates an issue with the underlying storage provisioner or PV definition."
        echo ""
        echo "DataVolume details:"
        oc get dv "${DV_NAME}" -n "${NAMESPACE}" -o yaml
        echo ""
        echo "PVC details:"
        oc get pvc "${DV_NAME}" -n "${NAMESPACE}" -o yaml
        echo ""
        echo "Leaving DataVolume and PVC in place for investigation. To clean up, run:"
        echo "  oc delete dv ${DV_NAME} -n ${NAMESPACE}"
        exit 1
    fi
done

# End of file
