---

{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ include "kubevela.serviceAccountName" . }}
  labels:
    {{- include "kubevela.labels" . | nindent 4 }}
  {{- with .Values.serviceAccount.annotations }}
  annotations:
  {{- toYaml . | nindent 4 }}
  {{- end }}
{{- end }}

---


apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: {{ include "kubevela.fullname" . }}:manager-rolebinding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: {{ if .Values.authentication.enabled }} {{ include "kubevela.fullname" . }}:manager {{ else }} "cluster-admin" {{ end }}
subjects:
  - kind: ServiceAccount
    name: {{ include "kubevela.serviceAccountName" . }}
    namespace: {{ .Release.Namespace }}

{{ if .Values.authentication.enabled }}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: {{ include "kubevela.fullname" . }}:manager
rules:
  - apiGroups: ["core.oam.dev", "terraform.core.oam.dev", "prism.oam.dev", "standard.oam.dev"]
    resources: ["*"]
    verbs: ["*"]
  - apiGroups: ["cluster.open-cluster-management.io"]
    resources: ["managedclusters"]
    verbs: ["get", "list", "watch"]
  - apiGroups: [""]
    resources: ["users", "groups", "serviceaccounts"]
    verbs: ["impersonate"]
  - apiGroups: [""]
    resources: ["namespaces", "secrets", "services"]
    verbs: ["get", "watch", "list"]
  - apiGroups: [""]
    resources: ["configmaps", "events"]
    verbs: ["*"]
  - apiGroups: ["apps"]
    resources: ["controllerrevisions"]
    verbs: ["*"]
  - apiGroups: ["apiregistration.k8s.io"]
    resources: ["apiservices"]
    verbs: ["get", "list", "watch", "update"]
  - apiGroups: ["coordination.k8s.io"]
    resources: ["leases"]
    verbs: ["*"]
  - apiGroups: ["admissionregistration.k8s.io"]
    resources: ["mutatingwebhookconfigurations", "validatingwebhookconfigurations"]
    verbs: ["get", "list", "watch"]
  - apiGroups: ["flowcontrol.apiserver.k8s.io"]
    resources: ["prioritylevelconfigurations", "flowschemas"]
    verbs: ["get", "list", "watch"]
  - apiGroups: ["authorization.k8s.io"]
    resources: ["subjectaccessreviews"]
    verbs: ["*"]
{{ end }}

---
# permissions to do leader election.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: {{ include "kubevela.fullname" . }}:leader-election-role
rules:
  - apiGroups:
      - ""
    resources:
      - configmaps
    verbs:
      - get
      - list
      - watch
      - create
      - update
      - patch
      - delete
  - apiGroups:
      - ""
    resources:
      - configmaps/status
    verbs:
      - get
      - update
      - patch
  - apiGroups:
      - ""
    resources:
      - events
    verbs:
      - create

---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: {{ include "kubevela.fullname" . }}:leader-election-rolebinding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: {{ include "kubevela.fullname" . }}:leader-election-role
subjects:
  - kind: ServiceAccount
    name: {{ include "kubevela.serviceAccountName" . }}

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "kubevela.fullname" . }}
  namespace: {{ .Release.Namespace }}
  labels:
    controller.oam.dev/name: vela-core
  {{- include "kubevela.labels" . | nindent 4 }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
  {{- include "kubevela.selectorLabels" . | nindent 6 }}
  template:
    metadata:
      labels:
    {{- include "kubevela.selectorLabels" . | nindent 8 }}
      annotations:
          prometheus.io/path: /metrics
          prometheus.io/port: "8080"
          prometheus.io/scrape: "true"
    spec:
      {{- with .Values.imagePullSecrets }}
      imagePullSecrets:
      {{- toYaml . | nindent 8 }}
      {{- end }}
      serviceAccountName: {{ include "kubevela.serviceAccountName" . }}
      securityContext:
      {{- toYaml .Values.podSecurityContext | nindent 8 }}
      containers:
        - name: {{ .Release.Name }}
          securityContext:
          {{- toYaml .Values.securityContext | nindent 12 }}
          args:
            - "--metrics-addr=:8080"
            - "--enable-leader-election"
            {{ if ne .Values.logFilePath "" }}
            - "--log-file-path={{ .Values.logFilePath }}"
            - "--log-file-max-size={{ .Values.logFileMaxSize }}"
            {{ end }}
            {{ if .Values.logDebug }}
            - "--log-debug=true"
            {{ end }}
            {{ if .Values.admissionWebhooks.enabled }}
            - "--use-webhook=true"
            - "--webhook-port={{ .Values.webhookService.port }}"
            - "--webhook-cert-dir={{ .Values.admissionWebhooks.certificate.mountPath }}"
            - "--autogen-workload-definition={{ .Values.admissionWebhooks.autoGenWorkloadDefinition }}"
            {{ end }}
            - "--health-addr=:{{ .Values.healthCheck.port }}"
            - "--apply-once-only={{ .Values.applyOnceOnly }}"
            {{ if ne .Values.disableCaps "" }}
            - "--disable-caps={{ .Values.disableCaps }}"
            {{ end }}
            - "--system-definition-namespace={{ include "systemDefinitionNamespace" . }}"
            - "--application-revision-limit={{ .Values.applicationRevisionLimit }}"
            - "--definition-revision-limit={{ .Values.definitionRevisionLimit }}"
            - "--oam-spec-ver={{ .Values.OAMSpecVer }}"
            {{ if .Values.multicluster.enabled }}
            - "--enable-cluster-gateway"
            {{ end }}
            - "--concurrent-reconciles={{ .Values.concurrentReconciles }}"
            - "--kube-api-qps={{ .Values.kubeClient.qps }}"
            - "--kube-api-burst={{ .Values.kubeClient.burst }}"
            - "--max-workflow-wait-backoff-time={{ .Values.workflow.backoff.maxTime.waitState }}"
            - "--max-workflow-failed-backoff-time={{ .Values.workflow.backoff.maxTime.failedState }}"
            - "--max-workflow-step-error-retry-times={{ .Values.workflow.step.errorRetryTimes }}"
            - "--feature-gates=EnableSuspendOnFailure={{- .Values.workflow.enableSuspendOnFailure | toString -}}"
            - "--feature-gates=AuthenticateApplication={{- .Values.authentication.enabled | toString -}}"
            {{ if .Values.authentication.enabled }}
            {{ if .Values.authentication.withUser }}
            - "--authentication-with-user"
            {{ end }}
            - "--authentication-default-user={{ .Values.authentication.defaultUser }}"
            - "--authentication-group-pattern={{ .Values.authentication.groupPattern }}"
            {{ end }}
          image: {{ .Values.imageRegistry }}{{ .Values.image.repository }}:{{ .Values.image.tag }}
          imagePullPolicy: {{ quote .Values.image.pullPolicy }}
          resources:
          {{- toYaml .Values.resources | nindent 12 }}
          {{ if .Values.admissionWebhooks.enabled }}
          ports:
            - containerPort: {{ .Values.webhookService.port }}
              name: webhook-server
              protocol: TCP
            - containerPort: {{ .Values.healthCheck.port }}
              name: healthz
              protocol: TCP
          readinessProbe:
            httpGet:
              path: /readyz
              port: healthz
            initialDelaySeconds: 30
            periodSeconds: 5
          livenessProbe:
            httpGet:
              path: /healthz
              port: healthz
            initialDelaySeconds: 90
            periodSeconds: 5
          volumeMounts:
            - mountPath: {{ .Values.admissionWebhooks.certificate.mountPath }}
              name: tls-cert-vol
              readOnly: true
          {{ end }}
      {{ if .Values.admissionWebhooks.enabled }}
      volumes:
        - name: tls-cert-vol
          secret:
            defaultMode: 420
            secretName: {{ template "kubevela.fullname" . }}-admission
      {{ end }}
      {{- with .Values.nodeSelector }}
      nodeSelector:
      {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.affinity }}
      affinity:
      {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.tolerations }}
      tolerations:
    {{- toYaml . | nindent 8 }}
  {{- end }}