#!/usr/bin/env bash
set -euo pipefail

namespace="cert-manager"
selectors=(
  "app.kubernetes.io/name=cert-manager"
  "app.kubernetes.io/instance=cert-manager"
  "app.kubernetes.io/instance=certmanager-prod"
)

delete_namespaced() {
  local selector="$1"
  kubectl -n "${namespace}" delete deployment,daemonset,statefulset,replicaset \
    --selector "${selector}" --ignore-not-found --wait=false
  kubectl -n "${namespace}" delete pod,service,endpoints,serviceaccount,configmap,secret \
    --selector "${selector}" --ignore-not-found --wait=false
  kubectl -n "${namespace}" delete role,rolebinding \
    --selector "${selector}" --ignore-not-found --wait=false
  kubectl -n "${namespace}" delete job,cronjob \
    --selector "${selector}" --ignore-not-found --wait=false
}

delete_cluster_scoped() {
  local selector="$1"
  kubectl delete clusterrole,clusterrolebinding \
    --selector "${selector}" --ignore-not-found --wait=false
  kubectl delete mutatingwebhookconfiguration,validatingwebhookconfiguration \
    --selector "${selector}" --ignore-not-found --wait=false
}

for selector in "${selectors[@]}"; do
  delete_namespaced "${selector}"
  delete_cluster_scoped "${selector}"
done

kubectl delete mutatingwebhookconfiguration cert-manager-webhook --ignore-not-found --wait=false
kubectl delete validatingwebhookconfiguration cert-manager-webhook --ignore-not-found --wait=false
