{{- if .Values.serviceAccount.create }}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ template "teleport-kube-agent.deleteHookServiceAccountName" . }}
  namespace: {{ .Release.Namespace }}
  annotations:
    "helm.sh/hook": post-delete
    "helm.sh/hook-weight": "-4"
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
---
{{- end }}
{{- if .Values.rbac.create }}
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: {{ .Release.Name }}-delete-hook
  namespace: {{ .Release.Namespace }}
  annotations:
    "helm.sh/hook": post-delete
    "helm.sh/hook-weight": "-3"
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
rules:
  - apiGroups: [""]
    resources: ["secrets",]
    verbs: ["get", "delete", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: {{ .Release.Name }}-delete-hook
  namespace: {{ .Release.Namespace }}
  annotations:
    "helm.sh/hook": post-delete
    "helm.sh/hook-weight": "-2"
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: {{ .Release.Name }}-delete-hook
subjects:
- kind: ServiceAccount
  name: {{ .Release.Name }}-delete-hook
  namespace: {{ .Release.Namespace }}
---
{{- end }}
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ .Release.Name }}-delete-hook
  namespace: {{ .Release.Namespace }}
  annotations:
    "helm.sh/hook": post-delete
    "helm.sh/hook-weight": "-1"
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
  template:
    metadata:
      name: {{ .Release.Name }}-delete-hook
    spec:
{{- if .Values.imagePullSecrets }}
      imagePullSecrets:
  {{- toYaml .Values.imagePullSecrets | nindent 6 }}
{{- end }}
{{- if .Values.priorityClassName }}
      priorityClassName: {{ .Values.priorityClassName }}
{{- end }}
      serviceAccountName: {{ template "teleport-kube-agent.deleteHookServiceAccountName" . }}
      restartPolicy: OnFailure
{{- if .Values.tolerations }}
      tolerations:
        {{- toYaml .Values.tolerations | nindent 6 }}
{{- end }}
{{- if .Values.nodeSelector }}
      nodeSelector:
        {{- toYaml .Values.nodeSelector | nindent 8 }}
{{- end }}
      containers:
      - name: post-delete-job
        env:
          - name: KUBE_NAMESPACE
            valueFrom:
              fieldRef:
                fieldPath: metadata.namespace
          - name: RELEASE_NAME
            value: {{ .Release.Name }}
        image: {{ include "teleport-kube-agent.image" . | quote }}
        {{- if .Values.imagePullPolicy }}
        imagePullPolicy: {{ toYaml .Values.imagePullPolicy }}
        {{- end }}
        command: ["teleport"]
        args: ["kube-state", "delete"]
        {{- if .Values.securityContext }}
        securityContext: {{- toYaml .Values.securityContext | nindent 10 }}
        {{- end }}
