#!/bin/bash

#kubectl --namespace rook-ceph delete cephcluster rook-ceph --wait

#helm --namespace rook-ceph uninstall rook-ceph

CLUSTER=$1
OPERATOR=$1-o
NAMESPACE=$1

echo "Patching cluster $CLUSTER to allow deletes"
echo kubectl --namespace ${NAMESPACE} patch cephcluster ${NAMESPACE} --type merge -p '{"spec":{"cleanupPolicy":{"confirmation":"yes-really-destroy-data"}}}'
kubectl --namespace ${NAMESPACE} patch cephcluster ${NAMESPACE} --type merge -p '{"spec":{"cleanupPolicy":{"confirmation":"yes-really-destroy-data"}}}'

for CRD in $(kubectl get crd -n rook-ceph | awk '/ceph.rook.io/ {print $1}'); do
    kubectl get -n rook-ceph "$CRD" -o name | \
    xargs -I {} kubectl patch -n rook-ceph {} --type merge -p '{"metadata":{"finalizers": []}}'
done

kubectl -n rook-ceph patch configmap rook-ceph-mon-endpoints --type merge -p '{"metadata":{"finalizers": []}}'
kubectl -n rook-ceph patch secrets rook-ceph-mon --type merge -p '{"metadata":{"finalizers": []}}'

kubectl delete storageclasses ceph-block ceph-bucket ceph-filesystem --wait

kubectl --namespace ${NAMESPACE} delete cephobjectstore ceph-objectstore --force
kubectl --namespace ${NAMESPACE} delete cephfilesystem ceph-filesystem --force
kubectl --namespace ${NAMESPACE} delete cephblockpools ceph-blockpool --force

kubectl --namespace ${NAMESPACE} delete cephcluster ${CLUSTER} --wait

helm --namespace ${NAMESPACE} uninstall ${CLUSTER}

kubectl delete ns ${NAMESPACE} --wait

for i in $(kubectl get crd | grep ceph | awk '{print $1}'); do kubectl delete crd $i ; done
for i in $(kubectl get crd | grep objectbucket | awk '{print $1}'); do kubectl delete crd $i ; done
for i in $(kubectl get clusterrole | grep ceph | awk '{print $1}'); do kubectl delete clusterrole $i ; done
for i in $(kubectl get clusterrole | grep rbd | awk '{print $1}'); do kubectl delete clusterrole $i ; done
for i in $(kubectl get clusterrole | grep objectstorage- | awk '{print $1}'); do kubectl delete clusterrole $i ; done
for i in $(kubectl get clusterrolebinding | grep -E '(ceph|rook|rbd-csi|objectstorage-prov)' | awk '{print $1}' ) ; do kubectl delete clusterrolebinding $i ; done

