# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

{{/* Define storage path configuration, please change it to your own path and make sure the path exists with the right permission*/}}
{{/* This path only works for local-path storage class */}}
{{- $hostBasePath := .Values.persistence.postgresqlHostLocalPath }}

{{- if .Values.postgresql.primary.persistence.enabled }}
{{- $name := "postgresql" }}
{{- $persistence := .Values.postgresql.primary.persistence }}
{{- $volumeName := printf "%s-data-pv" $name }}
{{- $claimName := printf "%s-data-pvc" $name }}
{{- $storageClass := $persistence.storageClass | default "local-path" }}
{{- $size := $persistence.size | default "10Gi" }}
{{- $hostPath := printf "%s/%s/%s" $hostBasePath $.Release.Name $name }}

{{/* Only create PV for local-path storage class */}}
{{- if and (eq $storageClass "local-path") (ne $hostBasePath "") }}
apiVersion: v1
kind: PersistentVolume
metadata:
  name: {{ $volumeName }}
  {{- if not $.Values.persistence.removeAfterUninstall }}
  annotations:
    "helm.sh/resource-policy": keep
  {{- end }}
  labels:
    type: local
    app: {{ $.Release.Name }}
    component: {{ $name }}
spec:
  storageClassName: {{ $storageClass }}
  capacity:
    storage: {{ $size }}
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  hostPath:
    path: {{ $hostPath }}
---
{{- end }}
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: {{ $claimName }}
  namespace: {{ $.Release.Namespace }}
  {{- if not $.Values.persistence.removeAfterUninstall }}
  annotations:
    "helm.sh/resource-policy": keep
  {{- end }}
  labels:
    app: {{ $.Release.Name }}
    component: {{ $name }}
spec:
  storageClassName: {{ $storageClass }}
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: {{ $size }}
  {{- if and (eq $storageClass "local-path") (ne $hostBasePath "") }}
  volumeName: {{ $volumeName }}
  {{- end }}
{{- end }} 