{{- if .Values.controller-manager.webhook.enabled }}
{{- $isCertManager := or (.Capabilities.APIVersions.Has "cert-manager.io/v1beta1") (.Capabilities.APIVersions.Has "cert-manager.io/v1alpha2") (.Capabilities.APIVersions.Has "certmanager.k8s.io/v1alpha1") (.Capabilities.APIVersions.Has "cert-manager.io/v1") }}
{{- $certManagerApiVersion := "cert-manager.io/v1" }}
{{- if or (.Capabilities.APIVersions.Has "cert-manager.io/v1") }}
{{- $certManagerApiVersion = "cert-manager.io/v1" }}
{{- else if or (.Capabilities.APIVersions.Has "cert-manager.io/v1beta1") }}
{{- $certManagerApiVersion = "cert-manager.io/v1beta1" }} 
{{- else if or (.Capabilities.APIVersions.Has "cert-manager.io/v1alpha2") }}
{{- $certManagerApiVersion = "cert-manager.io/v1alpha2" }}
{{- else if or (.Capabilities.APIVersions.Has "certmanager.k8s.io/v1alpha1") }}
{{- $certManagerApiVersion = "cert-manager.io/v1alpha1" }}
{{- end }}
{{- $ca := genCA "self-signed-ca" 3650 }}
{{- $cn := printf "%s-extensions-museum" .Release.Name }}
{{- $altName1 := printf "kubekey-webhook-service.%s" .Release.Namespace }}
{{- $altName2 := printf "kubekey-webhook-service.%s.svc" .Release.Namespace }}
{{- $cert := genSignedCert $cn nil (list $altName1 $altName2) 3650 $ca }}
{{- if $isCertManager }}
---
apiVersion: {{ $certManagerApiVersion }}
kind: Issuer
metadata:
  name: kubekey-selfsigned-issuer
  namespace: {{ .Release.Namespace }}
spec:
  selfSigned: {}
---
apiVersion: {{ $certManagerApiVersion }}
kind: Certificate
metadata:
  name: kubekey-serving-cert
  namespace: {{ .Release.Namespace }}
spec:
  dnsNames:
  - kubekey-webhook-service.{{ .Release.Namespace }}
  - kubekey-webhook-service.{{ .Release.Namespace }}.svc
  issuerRef:
    kind: Issuer
    name: kubekey-selfsigned-issuer
  secretName: kubekey-webhook-service-cert
{{- else }}  
---
apiVersion: v1
kind: Secret
metadata:
  name: kubekey-webhook-service-cert
  namespace: {{ .Release.Namespace }}
type: kubernetes.io/tls
data:
  ca.crt: {{ b64enc $ca.Cert }}
  tls.crt: {{ b64enc $cert.Cert }}
  tls.key: {{ b64enc $cert.Key }}
{{- end }}
---
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
  name: default-kubekey
  namespace: {{ .Release.Namespace }}
  {{- if $isCertManager }}
  annotations:
    cert-manager.io/inject-ca-from: {{ .Release.Namespace }}/kubekey-serving-cert
  {{- end }}
webhooks:
- admissionReviewVersions:
  - v1
  clientConfig:
    service:
      name: kk-webhook-service
      namespace: {{ .Release.Namespace }}
      path: /mutate-kubekey-kubesphere-io-v1beta1-playbook
    {{- if not $isCertManager }}
    caBundle: {{ b64enc $ca.Cert }}
    {{- end }}
  failurePolicy: Fail
  name: default.playbook.kubekey.kubesphere.io
  rules:
  - apiGroups:
    - kubekey.kubesphere.io
    apiVersions:
    - v1beta1
    operations:
    - CREATE
    - UPDATE
    resources:
    - playbooks
  sideEffects: None
{{- end }}