{{- $shouldUpdateCerts := true }}
{{- $configMap := lookup "v1" "ConfigMap" .Release.Namespace "etcd-deployed-version" }}
{{- if $configMap }}
  {{- $deployedVersion := index $configMap "data" "version" }}
  {{- if $deployedVersion | semverCompare ">= 2.6.1" }}
    {{- $shouldUpdateCerts = false }}
  {{- end }}
{{- end }}

{{- if $shouldUpdateCerts }}
---
apiVersion: batch/v1
kind: Job
metadata:
  name: etcd-hook
  annotations:
    helm.sh/hook: post-upgrade
    helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
spec:
  template:
    metadata:
      labels:
        policy.cozystack.io/allow-to-apiserver: "true"
    spec:
      serviceAccountName: etcd-hook
      containers:
        - name: kubectl
          image: bitnami/kubectl:latest
          command:
          - sh
          args:
            - -exc
            - |-
              kubectl --namespace={{ .Release.Namespace }} delete secrets etcd-ca-tls etcd-peer-ca-tls 
              sleep 10
              kubectl --namespace={{ .Release.Namespace }} delete secrets etcd-client-tls etcd-peer-tls etcd-server-tls
              kubectl --namespace={{ .Release.Namespace }} delete pods --selector=app.kubernetes.io/instance=etcd,app.kubernetes.io/managed-by=etcd-operator,app.kubernetes.io/name=etcd,cozystack.io/service=etcd
      restartPolicy: Never
{{- end }}
