#!/bin/bash
attempt=1
while true; do
    echo "Attempt: $attempt"
   
    kubectl -n openshift-gitops patch app cm-app -p '{"metadata":{"finalizers":null}}' --type=merge 2>/dev/null || true
    kubectl -n openshift-gitops delete app cm-app --ignore-not-found=true 2>/dev/null || true    
    kubectl delete -f https://raw.githubusercontent.com/mytreya-rh/external-secrets-gitops/refs/heads/main/cm_istio/og.yaml --ignore-not-found=true 2>/dev/null || true
    kubectl delete namespace istio-system --ignore-not-found=true 2>/dev/null || true
    kubectl -n cert-manager-operator delete subscriptions.operators.coreos.com cert-manager-operator 2>/dev/null || true
    kubectl -n cert-manager-operator delete operatorgroup cm-operator-group 2>/dev/null || true
    kubectl delete namespace cert-manager-operator --ignore-not-found=true 2>/dev/null || true
    kubectl delete namespace cert-manager --ignore-not-found=true 2>/dev/null || true
    kubectl delete crd `kubectl get crd | grep cert-manager | awk '{print $1}'` --ignore-not-found=true 2>/dev/null || true
    kubectl delete crd `kubectl get crd | grep istio | awk '{print $1}'` --ignore-not-found=true 2>/dev/null || true
    kubectl create namespace istio-system
    kubectl create -f permissions.yaml
    kubectl apply -f app.yaml
    sleep 180
    kubectl -n istio-system get deployment cert-manager-istio-csr
    if [ $? -eq 1 ]; then
        echo "Race condition reproduced"
        echo "Attempt: $attempt"
         break
    fi
    attempt=$((attempt+1))
done
