{{- if .Values.server.statefulSet.enabled -}}
apiVersion: apps/v1
kind: StatefulSet
metadata:
{{- if .Values.server.statefulSet.annotations }}
  annotations:
    {{ toYaml .Values.server.statefulSet.annotations | nindent 4 }}
{{- end }}
  labels:
    {{- include "prometheus.server.labels" . | nindent 4 }}
    {{- if .Values.server.statefulSet.labels}}
    {{ toYaml .Values.server.statefulSet.labels | nindent 4 }}
    {{- end}}
  name: {{ template "prometheus.server.fullname" . }}
  namespace: {{ include "prometheus.namespace" . }}
spec:
  {{- if semverCompare ">= 1.27.x" (include "prometheus.kubeVersion" .) }}
  persistentVolumeClaimRetentionPolicy:
    whenDeleted: {{ ternary "Delete" "Retain" .Values.server.statefulSet.pvcDeleteOnStsDelete }}
    whenScaled: {{ ternary "Delete" "Retain" .Values.server.statefulSet.pvcDeleteOnStsScale }}
  {{- end }}
  serviceName: {{ template "prometheus.server.fullname" . }}-headless
  selector:
    matchLabels:
      {{- include "prometheus.server.matchLabels" . | nindent 6 }}
  replicas: {{ .Values.server.replicaCount }}
  revisionHistoryLimit: {{ .Values.server.revisionHistoryLimit }}
  podManagementPolicy: {{ .Values.server.statefulSet.podManagementPolicy }}
  template:
    metadata:
    {{- if .Values.server.podAnnotations }}
      annotations:
        {{ toYaml .Values.server.podAnnotations | nindent 8 }}
    {{- end }}
      labels:
        {{- include "prometheus.server.labels" . | nindent 8 }}
        {{- if .Values.server.podLabels}}
        {{ toYaml .Values.server.podLabels | nindent 8 }}
        {{- end}}
    spec:
{{- if .Values.server.priorityClassName }}
      priorityClassName: "{{ .Values.server.priorityClassName }}"
{{- end }}
{{- if .Values.server.schedulerName }}
      schedulerName: "{{ .Values.server.schedulerName }}"
{{- end }}
{{- if semverCompare ">=1.13-0" .Capabilities.KubeVersion.GitVersion }}
      {{- if or (.Values.server.enableServiceLinks) (eq (.Values.server.enableServiceLinks | toString) "<nil>") }}
      enableServiceLinks: true
      {{- else }}
      enableServiceLinks: false
      {{- end }}
{{- end }}
      serviceAccountName: {{ template "prometheus.serviceAccountName.server" . }}
{{- if kindIs "bool" .Values.server.automountServiceAccountToken }}
      automountServiceAccountToken: {{ .Values.server.automountServiceAccountToken }}
{{- end }}
      {{- if .Values.server.extraInitContainers }}
      initContainers:
{{ toYaml .Values.server.extraInitContainers | indent 8 }}
      {{- end }}
      containers:
        {{- if .Values.configmapReload.prometheus.enabled }}
        - name: {{ template "prometheus.name" . }}-{{ .Values.server.name }}-{{ .Values.configmapReload.prometheus.name }}
          {{- if .Values.configmapReload.prometheus.image.digest }}
          image: "{{ .Values.configmapReload.prometheus.image.repository }}@{{ .Values.configmapReload.prometheus.image.digest }}"
          {{- else }}
          image: "{{ .Values.configmapReload.prometheus.image.repository }}:{{ .Values.configmapReload.prometheus.image.tag }}"
          {{- end }}
          imagePullPolicy: "{{ .Values.configmapReload.prometheus.image.pullPolicy }}"
          {{- with .Values.configmapReload.prometheus.containerSecurityContext }}
          securityContext:
            {{- toYaml . | nindent 12 }}
          {{- end }}
          args:
            - --watched-dir=/etc/config
          {{- $default_url := "http://127.0.0.1:9090/-/reload" }}
          {{- with .Values.server.prefixURL }}
          {{- $default_url = printf "http://127.0.0.1:9090%s/-/reload" . }}
          {{- end }}
          {{- if .Values.configmapReload.prometheus.containerPort }}
            - --listen-address=0.0.0.0:{{ .Values.configmapReload.prometheus.containerPort }}
          {{- end }}
            - --reload-url={{ default $default_url .Values.configmapReload.reloadUrl }}
          {{- range $key, $value := .Values.configmapReload.prometheus.extraArgs }}
            {{- if $value }}
            - --{{ $key }}={{ $value }}
            {{- else }}
            - --{{ $key }}
            {{- end }}
          {{- end }}
          {{- range .Values.configmapReload.prometheus.extraVolumeDirs }}
            - --watched-dir={{ . }}
          {{- end }}
          {{- with .Values.configmapReload.env }}
          env:
            {{- toYaml . | nindent 12 }}
          {{- end }}
          {{- if .Values.configmapReload.prometheus.containerPort }}
          ports:
            - containerPort: {{ .Values.configmapReload.prometheus.containerPort }}
              {{- if .Values.configmapReload.prometheus.containerPortName }}
              name: {{ .Values.configmapReload.prometheus.containerPortName }}
              {{- end }}
          {{- end }}
          {{- with .Values.configmapReload.prometheus.livenessProbe }}
          livenessProbe:
            {{- toYaml . | nindent 12 }}
          {{- end }}
          {{- with .Values.configmapReload.prometheus.readinessProbe }}
          readinessProbe:
            {{- toYaml . | nindent 12 }}
          {{- end }}
          {{- if .Values.configmapReload.prometheus.startupProbe }}
          {{- $startupProbe := omit .Values.configmapReload.prometheus.startupProbe "enabled" }}
          startupProbe:
            {{- toYaml $startupProbe | nindent 12 }}
          {{- end }}
          {{- with .Values.configmapReload.prometheus.resources }}
          resources:
            {{- toYaml . | nindent 12 }}
          {{- end }}
          volumeMounts:
            - name: config-volume
              mountPath: /etc/config
              readOnly: true
          {{- with .Values.configmapReload.prometheus.extraVolumeMounts }}
            {{- toYaml . | nindent 12 }}
          {{- end }}
          {{- range .Values.configmapReload.prometheus.extraConfigmapMounts }}
            - name: {{ $.Values.configmapReload.prometheus.name }}-{{ .name }}
              mountPath: {{ .mountPath }}
              subPath: {{ .subPath }}
              readOnly: {{ .readOnly }}
          {{- end }}
        {{- end }}

        - name: {{ template "prometheus.name" . }}-{{ .Values.server.name }}
          {{- if .Values.server.image.digest }}
          image: "{{ .Values.server.image.repository }}@{{ .Values.server.image.digest }}"
          {{- else }}
          image: "{{ .Values.server.image.repository }}:{{ .Values.server.image.tag | default .Chart.AppVersion }}"
          {{- end }}
          imagePullPolicy: "{{ .Values.server.image.pullPolicy }}"
          {{- with .Values.server.command }}
          command:
            {{- toYaml . | nindent 12 }}
          {{- end }}
          {{- if .Values.server.env }}
          env:
{{ toYaml .Values.server.env | indent 12}}
          {{- end }}
          args:
        {{- if .Values.server.defaultFlagsOverride }}
        {{ toYaml .Values.server.defaultFlagsOverride | nindent 12}}
        {{- else }}
          {{- if .Values.server.prefixURL }}
            - --web.route-prefix={{ .Values.server.prefixURL }}
          {{- end }}
          {{- if .Values.server.retention }}
            - --storage.tsdb.retention.time={{ .Values.server.retention }}
          {{- end }}
          {{- if .Values.server.retentionSize }}
            - --storage.tsdb.retention.size={{ .Values.server.retentionSize }}
          {{- end }}
            - --config.file={{ .Values.server.configPath }}
          {{- if .Values.server.storagePath }}
            - --storage.tsdb.path={{ .Values.server.storagePath }}
          {{- else }}
            - --storage.tsdb.path={{ .Values.server.persistentVolume.mountPath }}
          {{- end }}
            - --web.console.libraries=/etc/prometheus/console_libraries
            - --web.console.templates=/etc/prometheus/consoles
          {{- range .Values.server.extraFlags }}
            - --{{ . }}
          {{- end }}
          {{- range $key, $value := .Values.server.extraArgs }}
            {{- if $value }}
            - --{{ $key }}={{ $value }}
            {{- else }}
            - --{{ $key }}
            {{- end }}
          {{- end }}
          {{- if .Values.server.baseURL }}
            - --web.external-url={{ .Values.server.baseURL }}
          {{- end }}
        {{- end }}
          ports:
            - containerPort: 9090
          {{- if .Values.server.portName }}
              name: {{ .Values.server.portName }}
          {{- end }}
          {{- if .Values.server.hostPort }}
              hostPort: {{ .Values.server.hostPort }}
          {{- end }}
          readinessProbe:
            {{- if not .Values.server.tcpSocketProbeEnabled }}
            httpGet:
              path: {{ .Values.server.prefixURL }}/-/ready
              port: 9090
              scheme: {{ .Values.server.probeScheme }}
              {{- with .Values.server.probeHeaders }}
              httpHeaders:
{{- toYaml . | nindent 14 }}
              {{- end }}
            {{- else }}
            tcpSocket:
              port: 9090
            {{- end }}
            initialDelaySeconds: {{ .Values.server.readinessProbeInitialDelay }}
            periodSeconds: {{ .Values.server.readinessProbePeriodSeconds }}
            timeoutSeconds: {{ .Values.server.readinessProbeTimeout }}
            failureThreshold: {{ .Values.server.readinessProbeFailureThreshold }}
            successThreshold: {{ .Values.server.readinessProbeSuccessThreshold }}
          livenessProbe:
            {{- if not .Values.server.tcpSocketProbeEnabled }}
            httpGet:
              path: {{ .Values.server.prefixURL }}/-/healthy
              port: 9090
              scheme: {{ .Values.server.probeScheme }}
              {{- with .Values.server.probeHeaders }}
              httpHeaders:
{{- toYaml . | nindent 14 }}
              {{- end }}
            {{- else }}
            tcpSocket:
              port: 9090
            {{- end }}
            initialDelaySeconds: {{ .Values.server.livenessProbeInitialDelay }}
            periodSeconds: {{ .Values.server.livenessProbePeriodSeconds }}
            timeoutSeconds: {{ .Values.server.livenessProbeTimeout }}
            failureThreshold: {{ .Values.server.livenessProbeFailureThreshold }}
            successThreshold: {{ .Values.server.livenessProbeSuccessThreshold }}
          {{- if .Values.server.startupProbe.enabled }}
          startupProbe:
            {{- if not .Values.server.tcpSocketProbeEnabled }}
            httpGet:
              path: {{ .Values.server.prefixURL }}/-/healthy
              port: 9090
              scheme: {{ .Values.server.probeScheme }}
              {{- if .Values.server.probeHeaders }}
              httpHeaders:
              {{- range .Values.server.probeHeaders}}
              - name: {{ .name }}
                value: {{ .value }}
              {{- end }}
              {{- end }}
            {{- else }}
            tcpSocket:
              port: 9090
            {{- end }}
            failureThreshold: {{ .Values.server.startupProbe.failureThreshold }}
            periodSeconds: {{ .Values.server.startupProbe.periodSeconds }}
            timeoutSeconds: {{ .Values.server.startupProbe.timeoutSeconds }}
          {{- end }}
          {{- with .Values.server.resources }}
          resources:
            {{- toYaml . | nindent 12 }}
          {{- end }}
          volumeMounts:
            - name: config-volume
              mountPath: /etc/config
            - name: {{ ternary .Values.server.persistentVolume.statefulSetNameOverride "storage-volume" (and .Values.server.persistentVolume.enabled (not (empty .Values.server.persistentVolume.statefulSetNameOverride))) }}
              mountPath: {{ .Values.server.persistentVolume.mountPath }}
              subPath: "{{ .Values.server.persistentVolume.subPath }}"
          {{- range .Values.server.extraHostPathMounts }}
            - name: {{ .name }}
              mountPath: {{ .mountPath }}
              subPath: {{ .subPath }}
              readOnly: {{ .readOnly }}
          {{- end }}
          {{- range .Values.server.extraConfigmapMounts }}
            - name: {{ $.Values.server.name }}-{{ .name }}
              mountPath: {{ .mountPath }}
              subPath: {{ .subPath }}
              readOnly: {{ .readOnly }}
          {{- end }}
          {{- range .Values.server.extraSecretMounts }}
            - name: {{ .name }}
              mountPath: {{ .mountPath }}
              subPath: {{ .subPath }}
              readOnly: {{ .readOnly }}
          {{- end }}
          {{- if .Values.server.extraVolumeMounts }}
          {{ toYaml .Values.server.extraVolumeMounts | nindent 12 }}
          {{- end }}
          {{- with .Values.server.containerSecurityContext }}
          securityContext:
            {{- toYaml . | nindent 12 }}
          {{- end }}
    {{- if .Values.server.sidecarContainers }}
      {{- range $name, $spec :=  .Values.server.sidecarContainers }}
        - name: {{ $name }}
          {{- if kindIs "string" $spec }}
            {{- tpl $spec $ | nindent 10 }}
          {{- else }}
            {{- toYaml $spec | nindent 10 }}
          {{- end }}
      {{- end }}
    {{- end }}
      hostNetwork: {{ .Values.server.hostNetwork }}
    {{- if .Values.server.dnsPolicy }}
      dnsPolicy: {{ .Values.server.dnsPolicy }}
    {{- end }}
    {{- if .Values.imagePullSecrets }}
      imagePullSecrets:
{{ toYaml .Values.imagePullSecrets | indent 8 }}
    {{- end }}
    {{- if .Values.server.nodeSelector }}
      nodeSelector:
{{ toYaml .Values.server.nodeSelector | indent 8 }}
    {{- end }}
    {{- if .Values.server.hostAliases }}
      hostAliases:
{{ toYaml .Values.server.hostAliases | indent 8 }}
    {{- end }}
    {{- if .Values.server.dnsConfig }}
      dnsConfig:
{{ toYaml .Values.server.dnsConfig | indent 8 }}
    {{- end }}
    {{- with .Values.server.securityContext }}
      securityContext:
        {{- toYaml . | nindent 8 }}
    {{- end }}
    {{- if .Values.server.tolerations }}
      tolerations:
{{ toYaml .Values.server.tolerations | indent 8 }}
    {{- end }}
    {{- if or .Values.server.affinity .Values.server.podAntiAffinity }}
      affinity:
    {{- end }}
      {{- with .Values.server.affinity }}
      {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- if eq .Values.server.podAntiAffinity "hard" }}
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            - topologyKey: {{ .Values.server.podAntiAffinityTopologyKey }}
              labelSelector:
                matchExpressions:
                  - {key: app.kubernetes.io/name, operator: In, values: [{{ template "prometheus.name" . }}]}
      {{- else if eq .Values.server.podAntiAffinity "soft" }}
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
            - weight: 100
              podAffinityTerm:
                topologyKey: {{ .Values.server.podAntiAffinityTopologyKey }}
                labelSelector:
                  matchExpressions:
                    - {key: app.kubernetes.io/name, operator: In, values: [{{ template "prometheus.name" . }}]}
      {{- end }}
    {{- with .Values.server.topologySpreadConstraints }}
      topologySpreadConstraints:
        {{- toYaml . | nindent 8 }}
    {{- end }}
      terminationGracePeriodSeconds: {{ .Values.server.terminationGracePeriodSeconds }}
      volumes:
        - name: config-volume
        {{- if empty .Values.server.configFromSecret }}
          configMap:
            name: {{ if .Values.server.configMapOverrideName }}{{ .Release.Name }}-{{ .Values.server.configMapOverrideName }}{{- else }}{{ template "prometheus.server.fullname" . }}{{- end }}
        {{- else }}
          secret:
            secretName: {{ .Values.server.configFromSecret }}
        {{- end }}
      {{- range .Values.server.extraHostPathMounts }}
        - name: {{ .name }}
          hostPath:
            path: {{ .hostPath }}
      {{- end }}
      {{- range .Values.configmapReload.prometheus.extraConfigmapMounts }}
        - name: {{ $.Values.configmapReload.prometheus.name }}-{{ .name }}
          configMap:
            name: {{ .configMap }}
      {{- end }}
      {{- range .Values.server.extraConfigmapMounts }}
        - name: {{ $.Values.server.name }}-{{ .name }}
          configMap:
            name: {{ .configMap }}
      {{- end }}
      {{- range .Values.server.extraSecretMounts }}
        - name: {{ .name }}
          secret:
            secretName: {{ .secretName }}
            {{- with .optional }}
            optional: {{ . }}
            {{- end }}
      {{- end }}
      {{- range .Values.configmapReload.prometheus.extraConfigmapMounts }}
        - name: {{ .name }}
          configMap:
            name: {{ .configMap }}
            {{- with .optional }}
            optional: {{ . }}
            {{- end }}
      {{- end }}
{{- if .Values.server.extraVolumes }}
{{ toYaml .Values.server.extraVolumes | indent 8}}
{{- end }}
{{- if .Values.server.persistentVolume.enabled }}
  volumeClaimTemplates:
    - apiVersion: v1
      kind: PersistentVolumeClaim
      metadata:
        name: {{ .Values.server.persistentVolume.statefulSetNameOverride | default "storage-volume" }}
        {{- if .Values.server.persistentVolume.annotations }}
        annotations:
{{ toYaml .Values.server.persistentVolume.annotations | indent 10 }}
        {{- end }}
        {{- if .Values.server.persistentVolume.labels }}
        labels:
{{ toYaml .Values.server.persistentVolume.labels | indent 10 }}
        {{- end }}
      spec:
        accessModes:
{{ toYaml .Values.server.persistentVolume.accessModes | indent 10 }}
        resources:
          requests:
            storage: "{{ .Values.server.persistentVolume.size }}"
      {{- if .Values.server.persistentVolume.storageClass }}
      {{- if (eq "-" .Values.server.persistentVolume.storageClass) }}
        storageClassName: ""
      {{- else }}
        storageClassName: "{{ .Values.server.persistentVolume.storageClass }}"
      {{- end }}
      {{- end }}
{{- else }}
        - name: storage-volume
          emptyDir:
          {{- if .Values.server.emptyDir.sizeLimit }}
            sizeLimit: {{ .Values.server.emptyDir.sizeLimit }}
          {{- else }}
            {}
          {{- end -}}
{{- end }}
{{- end }}
