{{- if not .Values.rbac.only }}
apiVersion: batch/v1
kind: Job
metadata:
  name: uninstall-agents
  namespace: {{ include "traffic-manager.namespace" . }}
  labels:
    app.kubernetes.io/managed-by: {{ .Release.Service | quote }}
    app.kubernetes.io/instance: {{ .Release.Name | quote }}
    app.kubernetes.io/version: {{ .Chart.AppVersion }}
    helm.sh/chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
  annotations:
    {{- /* This is what defines this resource as a hook. Without this line, the job is considered part of the release. */}}
    "helm.sh/hook": pre-delete
    "helm.sh/hook-weight": "-5"
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
  backoffLimit: 1
  template:
    metadata:
      name: uninstall-agents
      labels:
        app.kubernetes.io/managed-by: {{ .Release.Service | quote }}
        app.kubernetes.io/instance: {{ .Release.Name | quote }}
        helm.sh/chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    spec:
      securityContext:
        {{- toYaml .Values.hooks.podSecurityContext | nindent 8 }}
      restartPolicy: Never
      {{- with .Values.hooks.curl.imagePullSecrets }}
      imagePullSecrets:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      containers:
        - name: uninstall-agents
          securityContext:
            {{- if .Values.hooks.securityContext }}
            {{- toYaml .Values.hooks.securityContext | nindent 12 }}
            {{- else }}
            {{- toYaml .Values.securityContext | nindent 12 }}
            {{- end }}
          image: "{{ .Values.hooks.curl.registry }}/{{ .Values.hooks.curl.image }}:{{ .Values.hooks.curl.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          volumeMounts:
            - name: secret-volume
              mountPath: /secret
          env:
            - name: CURL_CA_BUNDLE
              value: /secret/ca.crt
          resources:
            {{- toYaml .Values.hooks.resources | nindent 12 }}
          command:
            - sh
            - -c
          args:
            - 'curl --fail --connect-timeout 5 --max-time 60 --request DELETE https://{{ .Values.agentInjector.name }}.{{ include "traffic-manager.namespace" . }}:{{ .Values.agentInjector.webhook.port }}/uninstall || exit 0'
      volumes:
        - name: secret-volume
          secret:
            secretName: {{ .Values.agentInjector.secret.name }}
      {{- with .Values.nodeSelector }}
      nodeSelector:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.affinity }}
      affinity:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.tolerations }}
      tolerations:
        {{- toYaml . | nindent 8 }}
      {{- end }}
{{- end }}
