# tls-init-cleanup job deletes Kubernetes secrets created by tls-init
{{- if (or (and (ne (.Values.server.enabled | toString) "-") .Values.server.enabled) (and (eq (.Values.server.enabled | toString) "-") .Values.global.enabled)) }}
{{- if .Values.global.tls.enabled }}
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ template "consul.fullname" . }}-tls-init-cleanup
  labels:
    app: {{ template "consul.name" . }}
    chart: {{ template "consul.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
  annotations:
    "helm.sh/hook": pre-delete
    "helm.sh/hook-delete-policy": hook-succeeded
spec:
  template:
    metadata:
      name: {{ template "consul.fullname" . }}-tls-init-cleanup
      labels:
        app: {{ template "consul.name" . }}
        chart: {{ template "consul.chart" . }}
        release: {{ .Release.Name }}
        component: tls-init-cleanup
      annotations:
        "consul.hashicorp.com/connect-inject": "false"
    spec:
      restartPolicy: Never
      serviceAccountName: {{ template "consul.fullname" . }}-tls-init-cleanup
      containers:
        - name: tls-init-cleanup
          image: "{{ .Values.global.image }}"
          env:
            - name: NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
          command:
            - "/bin/sh"
            - "-ec"
            - |
              {{- if (not (and .Values.global.tls.caCert.secretName .Values.global.tls.caKey.secretName)) }}
              curl -s -X DELETE --cacert /var/run/secrets/kubernetes.io/serviceaccount/ca.crt \
                https://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT}/api/v1/namespaces/${NAMESPACE}/secrets/{{ template "consul.fullname" . }}-ca-cert \
                -H "Authorization: Bearer $( cat /var/run/secrets/kubernetes.io/serviceaccount/token )"
              curl -s -X DELETE --cacert /var/run/secrets/kubernetes.io/serviceaccount/ca.crt \
                https://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT}/api/v1/namespaces/${NAMESPACE}/secrets/{{ template "consul.fullname" . }}-ca-key \
                -H "Authorization: Bearer $( cat /var/run/secrets/kubernetes.io/serviceaccount/token )"
              {{- end }}
              curl -s -X DELETE --cacert /var/run/secrets/kubernetes.io/serviceaccount/ca.crt \
                https://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT}/api/v1/namespaces/${NAMESPACE}/secrets/{{ template "consul.fullname" . }}-server-cert \
                -H "Authorization: Bearer $( cat /var/run/secrets/kubernetes.io/serviceaccount/token )"
{{- end }}
{{- end }}
