{{- /*
Copyright Broadcom, Inc. All Rights Reserved.
SPDX-License-Identifier: APACHE-2.0
*/}}

{{- if and .Values.pluginBarmanCloud.tls.autoGenerated.enabled (eq .Values.pluginBarmanCloud.tls.autoGenerated.engine "helm") }}
{{- $ca := genCA (include "cloudnative-pg.plugin-barman-cloud.fullname" .) 365 }}
{{- $altNames := list (include "cloudnative-pg.plugin-barman-cloud.fullname" .) "localhost" "127.0.0.1" }}
{{/* We create two certs, one for the client and another for the server. Depending on whether these are provided or not */}}
{{- $secrets := list }}
{{- if not .Values.pluginBarmanCloud.tls.server.existingSecret }}
{{- $secrets = append $secrets (
  dict
    "name" (printf "%s-server-crt" (include "cloudnative-pg.plugin-barman-cloud.fullname" .) | trunc 63 | trimSuffix "-")
    "cert" .Values.pluginBarmanCloud.tls.server.cert
    "key" .Values.pluginBarmanCloud.tls.server.key
    ) }}
{{- end }}
{{- if not .Values.pluginBarmanCloud.tls.client.existingSecret }}
{{- $secrets = append $secrets (
  dict
    "name" (printf "%s-client-crt" (include "cloudnative-pg.plugin-barman-cloud.fullname" .) | trunc 63 | trimSuffix "-")
    "cert" .Values.pluginBarmanCloud.tls.client.cert
    "key" .Values.pluginBarmanCloud.tls.client.key
    ) }}
{{- end }}
{{ range $secret := $secrets }}
{{- $secretName := $secret.name }}
{{- $autogenCert := genSignedCert (include "cloudnative-pg.plugin-barman-cloud.fullname" $) nil $altNames 365 $ca }}
---
apiVersion: v1
kind: Secret
metadata:
  name: {{ $secretName }}
  namespace: {{ include "common.names.namespace" $ | quote }}
  {{- /* Updating app.kubernetes.io/name because to avoid "duplicate deployment" error: https://github.com/cloudnative-pg/cloudnative-pg/blob/9c2769815ff78cbfc28e2a2818f3a04add33477c/pkg/certs/operator_deployment.go#L120 */}}
  {{- $appNameLabels := dict "app.kubernetes.io/name" "plugin-barman-cloud" }}
  {{- $labels := include "common.tplvalues.merge" ( dict "values" ( list $appNameLabels $.Values.commonLabels) "context" $ ) }}
  labels: {{- include "common.labels.standard" ( dict "customLabels" $labels "context" $ ) | nindent 4 }}
    app.kubernetes.io/part-of: cloudnative-pg
    app.kubernetes.io/component: plugin-barman-cloud
  {{- if $.Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" $.Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
type: kubernetes.io/tls
{{- if $.Values.pluginBarmanCloud.tls.autoGenerated.enabled }}
data:
  tls.crt: {{ include "common.secrets.lookup" (dict "secret" $secretName "key" "tls.crt" "defaultValue" $autogenCert.Cert "context" $) }}
  tls.key: {{ include "common.secrets.lookup" (dict "secret" $secretName "key" "tls.key" "defaultValue" $autogenCert.Key "context" $) }}
{{- else }}
data:
  tls.crt: {{ $secret.cert | b64enc | quote }}
  tls.key: {{ $secret.key | b64enc | quote }}
{{- end }}
{{- end }}
{{- end }}