#!/bin/bash
#
# Verification script for OCPBUGS-61452
# Make substitutions work for 4.21 in manifests of sriov-network-operator
#
# This script verifies that:
# 1. The art.yml file has been updated to reference 4.21 instead of 4.20
# 2. The olm.skipRange in CSV is correctly set
# 3. The operator can be installed/upgraded properly
#

set -e

NAMESPACE="openshift-sriov-network-operator"
OPERATOR_NAME="sriov-network-operator"

echo "=========================================="
echo "Verification for OCPBUGS-61452"
echo "=========================================="
echo ""

# Source login script if it exists
if [ -f ~/newlogin.sh ]; then
    source ~/newlogin.sh
fi

# Check if we're connected to a cluster
if ! oc cluster-info &>/dev/null; then
    echo "ERROR: Not connected to an OpenShift cluster"
    echo "Please login to your cluster first: oc login"
    exit 1
fi

echo "✓ Connected to cluster: $(oc cluster-info | head -1)"
echo ""

# Step 1: Check operator namespace exists
echo "Step 1: Checking operator namespace..."
if oc get namespace $NAMESPACE &>/dev/null; then
    echo "✓ Namespace '$NAMESPACE' exists"
else
    echo "⚠ Namespace '$NAMESPACE' not found. Operator may not be installed yet."
    echo "  You may need to install the operator first."
fi
echo ""

# Step 2: Check CSV and olm.skipRange
echo "Step 2: Verifying ClusterServiceVersion (CSV) and olm.skipRange..."
CSV=$(oc get csv -n $NAMESPACE -o name 2>/dev/null | grep $OPERATOR_NAME | head -1)

if [ -z "$CSV" ]; then
    echo "⚠ No CSV found for $OPERATOR_NAME in namespace $NAMESPACE"
    echo "  The operator may not be installed yet."
else
    echo "✓ Found CSV: $CSV"
    
    # Get the full CSV name
    CSV_NAME=$(echo $CSV | cut -d'/' -f2)
    
    # Check olm.skipRange annotation
    echo ""
    echo "Checking olm.skipRange annotation..."
    SKIP_RANGE=$(oc get csv $CSV_NAME -n $NAMESPACE -o jsonpath='{.metadata.annotations.olm\.skipRange}' 2>/dev/null || echo "")
    
    if [ -z "$SKIP_RANGE" ]; then
        echo "⚠ olm.skipRange annotation not found in CSV"
    else
        echo "✓ olm.skipRange found: $SKIP_RANGE"
        
        # Verify it references 4.21 (should not include 4.21 in the range)
        if echo "$SKIP_RANGE" | grep -q "4.21"; then
            echo "  ⚠ WARNING: olm.skipRange contains '4.21' - this may be incorrect"
            echo "    Expected format: '>=4.16.0-0 <4.21.0' (excluding 4.21)"
        else
            echo "  ✓ olm.skipRange does not include 4.21 (correct)"
        fi
        
        # Check if it's in the expected format
        if echo "$SKIP_RANGE" | grep -qE ">=4\.(1[6-9]|2[01])\.0-0 <4\.21"; then
            echo "  ✓ Format looks correct for 4.21"
        else
            echo "  ⚠ Format may need review"
        fi
    fi
    
    # Check CSV version
    CSV_VERSION=$(oc get csv $CSV_NAME -n $NAMESPACE -o jsonpath='{.spec.version}' 2>/dev/null || echo "")
    if [ -n "$CSV_VERSION" ]; then
        echo ""
        echo "CSV Version: $CSV_VERSION"
        
        # Check if version starts with 4.21
        if echo "$CSV_VERSION" | grep -qE "^4\.21\."; then
            echo "✓ CSV version is 4.21.x (correct)"
        else
            echo "⚠ CSV version is not 4.21.x (current: $CSV_VERSION)"
        fi
    fi
fi
echo ""

# Step 3: Check operator pods status
echo "Step 3: Checking operator pod status..."
PODS=$(oc get pods -n $NAMESPACE -o name 2>/dev/null | grep -E "(operator|controller)" || echo "")

if [ -z "$PODS" ]; then
    echo "⚠ No operator pods found in namespace $NAMESPACE"
else
    echo "Found operator pods:"
    for pod in $PODS; do
        POD_NAME=$(echo $pod | cut -d'/' -f2)
        STATUS=$(oc get pod $POD_NAME -n $NAMESPACE -o jsonpath='{.status.phase}' 2>/dev/null || echo "Unknown")
        READY=$(oc get pod $POD_NAME -n $NAMESPACE -o jsonpath='{.status.containerStatuses[0].ready}' 2>/dev/null || echo "false")
        
        if [ "$STATUS" = "Running" ] && [ "$READY" = "true" ]; then
            echo "  ✓ $POD_NAME: $STATUS (Ready)"
        else
            echo "  ⚠ $POD_NAME: $STATUS (Ready: $READY)"
        fi
    done
fi
echo ""

# Step 4: Check operator subscription
echo "Step 4: Checking operator subscription..."
SUBSCRIPTION=$(oc get subscription -n $NAMESPACE -o name 2>/dev/null | grep $OPERATOR_NAME | head -1 || echo "")

if [ -z "$SUBSCRIPTION" ]; then
    echo "⚠ No subscription found for $OPERATOR_NAME"
else
    SUB_NAME=$(echo $SUBSCRIPTION | cut -d'/' -f2)
    echo "✓ Found subscription: $SUB_NAME"
    
    # Get subscription details
    CHANNEL=$(oc get subscription $SUB_NAME -n $NAMESPACE -o jsonpath='{.spec.channel}' 2>/dev/null || echo "")
    SOURCE=$(oc get subscription $SUB_NAME -n $NAMESPACE -o jsonpath='{.spec.source}' 2>/dev/null || echo "")
    
    if [ -n "$CHANNEL" ]; then
        echo "  Channel: $CHANNEL"
        # Check if channel is for 4.21
        if echo "$CHANNEL" | grep -qE "(stable|fast|eus)-4\.21"; then
            echo "  ✓ Channel is for 4.21"
        else
            echo "  ⚠ Channel may not be for 4.21"
        fi
    fi
    
    if [ -n "$SOURCE" ]; then
        echo "  Source: $SOURCE"
    fi
fi
echo ""

# Step 5: Check for any OLM-related errors in events
echo "Step 5: Checking for OLM-related errors in events..."
RECENT_EVENTS=$(oc get events -n $NAMESPACE --sort-by='.lastTimestamp' 2>/dev/null | tail -10 || echo "")

if [ -n "$RECENT_EVENTS" ]; then
    ERROR_EVENTS=$(echo "$RECENT_EVENTS" | grep -iE "(error|fail|warning)" || echo "")
    if [ -n "$ERROR_EVENTS" ]; then
        echo "⚠ Found recent error/warning events:"
        echo "$ERROR_EVENTS" | head -5
    else
        echo "✓ No recent error events found"
    fi
else
    echo "⚠ Could not retrieve events"
fi
echo ""

# Step 6: Summary and recommendations
echo "=========================================="
echo "Verification Summary"
echo "=========================================="
echo ""
echo "To fully verify the fix, you should also:"
echo ""
echo "1. Check the source code/artifacts:"
echo "   - Verify that art.yml in the operator manifests has been updated"
echo "   - Search patterns should reference 4.21, not 4.20"
echo "   - PR: https://github.com/openshift/sriov-network-operator/pull/1142"
echo ""
echo "2. Test operator upgrade path:"
echo "   - If upgrading from 4.20, verify OLM correctly handles the upgrade"
echo "   - Check that versions in olm.skipRange are properly skipped"
echo ""
echo "3. Verify operator functionality:"
echo "   - Create SR-IOV network resources"
echo "   - Verify operator manages them correctly"
echo ""
echo "4. Check operator logs for any substitution-related errors:"
echo "   oc logs -n $NAMESPACE -l name=sriov-network-operator --tail=100"
echo ""
echo "=========================================="

