{{- $advanced := dict "start_listen_port" (.Values.service.wireguard.ports | sortAlpha | first | int) -}}
{{- $statistics := dict "listening_address" (printf ":%v" .Values.service.metrics.port) -}}
{{- $web:= dict "listening_address" (printf ":%v" .Values.service.web.port) -}}
{{- if and .Values.certificate.enabled (include "wg-portal.hostname" .) }}
  {{- $_ := set $web "cert_file" "/app/certs/tls.crt" }}
  {{- $_ := set $web "key_file" "/app/certs/tls.key" }}
{{- end }}

apiVersion: v1
kind: Secret
metadata:
  name: {{ include "wg-portal.fullname" . }}
  labels: {{- include "wg-portal.labels" . | nindent 4 }}
stringData:
  config.yml: |
    {{- with mustMerge $advanced .Values.config.advanced }}
    advanced: {{- tpl (toYaml .) $ | nindent 6 }}
    {{- end }}

    {{- with .Values.config.auth }}
    auth: {{- tpl (toYaml .) $ | nindent 6 }}
    {{- end }}

    {{- with mustMerge .Values.config.core (include "wg-portal.admin" . | fromYaml) }}
    core: {{- tpl (toYaml .) $ | nindent 6 }}
    {{- end }}

    {{- with .Values.config.database }}
    database: {{- tpl (toYaml .) $ | nindent 6 }}
    {{- end }}

    {{- with .Values.config.mail }}
    mail: {{- tpl (toYaml .) $ | nindent 6 }}
    {{- end }}

    {{- with mustMerge $statistics .Values.config.statistics }}
    statistics: {{- tpl (toYaml .) $ | nindent 6 }}
    {{- end }}

    {{- with mustMerge $web .Values.config.web }}
    web: {{- tpl (toYaml .) $ | nindent 6 }}
    {{- end }}
