{{- if not .Values.rbac.only }}
{{- $altNames := list ( printf "agent-injector.%s" (include "traffic-manager.namespace" .)) ( printf "agent-injector.%s.svc" (include "traffic-manager.namespace" .)) -}}
{{- $genCA := genCA "agent-injector-ca" 365 -}}
{{- $genCert := genSignedCert "agent-injector" nil $altNames 365 $genCA -}}
{{- $secretData := (lookup "v1" "Secret" (include "traffic-manager.namespace" .) .Values.agentInjector.secret.name).data -}}
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
  name: {{ .Values.agentInjector.webhook.name }}-{{ include "traffic-manager.namespace" . }}
  labels:
    {{- include "telepresence.labels" . | nindent 4 }}
webhooks:
{{- with .Values.agentInjector.webhook.admissionReviewVersions }}
- admissionReviewVersions:
  {{- toYaml . | nindent 2 }}
{{- end }}
  clientConfig:
{{- if and ($secretData) (not .Values.agentInjector.certificate.regenerate) }}
    caBundle: {{ or (get $secretData "ca.crt") (get $secretData "ca.pem") }}
{{- else }}
    caBundle: {{ $genCA.Cert | b64enc }}
{{- end }}
    service:
      name: {{ .Values.agentInjector.name }}
      namespace: {{ include "traffic-manager.namespace" . }}
      path: {{ .Values.agentInjector.webhook.servicePath }}
      port: {{ .Values.agentInjector.webhook.port }}
  rules:
  - apiGroups:
    - ""
    apiVersions:
    - v1
    operations:
    - CREATE
    - DELETE
    resources:
    - pods
    scope: '*'
  failurePolicy: {{ .Values.agentInjector.webhook.failurePolicy }}
  reinvocationPolicy: {{ .Values.agentInjector.webhook.reinvocationPolicy }}
  name: agent-injector-{{ include "traffic-manager.namespace" . }}.getambassador.io
  sideEffects: {{ .Values.agentInjector.webhook.sideEffects }}
  timeoutSeconds: {{ .Values.agentInjector.webhook.timeoutSeconds }}
  namespaceSelector:
{{- if .Values.managerRbac.namespaced }}
    matchExpressions:
{{- if and (eq (int (include "kube.version.major" .))  1) (lt (int (include "kube.version.minor" .)) 21) }}
      - key: app.kubernetes.io/name
{{- else }}
      - key: kubernetes.io/metadata.name
{{- end }}
        operator: In
        values:
{{- range .Values.managerRbac.namespaces }}
        - {{ . }}
{{- end }}
{{- else }}
{{ toYaml .Values.agentInjector.webhook.namespaceSelector | nindent 4 }}
{{- end }}
---
apiVersion: v1
kind: Secret
metadata:
  name: {{ .Values.agentInjector.secret.name }}
  namespace: {{ include "traffic-manager.namespace" . }}
  labels:
    {{- include "telepresence.labels" . | nindent 4 }}
data:
{{- if and ($secretData) (not .Values.agentInjector.certificate.regenerate) }}
  ca.crt: {{ or (get $secretData "ca.crt") (get $secretData "ca.pem") }}
  tls.crt: {{ or (get $secretData "tls.crt") (get $secretData "crt.pem") }}
  tls.key: {{ or (get $secretData "tls.key") (get $secretData "key.pem") }}
{{- else }}
  ca.crt: {{ $genCA.Cert | b64enc }}
  tls.crt: {{ $genCert.Cert | b64enc }}
  tls.key: {{ $genCert.Key | b64enc }}
{{- end }}
{{- end }}
