{{ if and .Release.IsInstall .Values.job.autoCreateCluster }}
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ template "stolon.fullname" . }}-create-cluster
  labels:
    app: {{ template "stolon.name" . }}
    chart: {{ template "stolon.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
  annotations:
    "helm.sh/hook-delete-policy": hook-succeeded
spec:
  template:
    metadata:
      labels:
        app: {{ template "stolon.fullname" . }}
        release: {{ .Release.Name }}
    spec:
      restartPolicy: OnFailure
      serviceAccountName: {{ template "stolon.serviceAccountName" . }}
  {{- if eq .Values.store.backend "etcdv2" "etcdv3" }}
      initContainers:
        - name: {{ .Chart.Name }}-etcd-wait
          image: "{{ .Values.etcdImage.repository }}:{{ .Values.etcdImage.tag }}"
          imagePullPolicy: {{ .Values.etcdImage.pullPolicy }}
          command: ["sh", "-c", "while ! etcdctl --endpoints {{ .Values.store.endpoints }} cluster-health; do sleep 1 && echo -n .; done"]
  {{- end }}
      containers:
        - name: {{ template "stolon.fullname" . }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          command: ["/usr/local/bin/stolonctl"]
          args:
            - init
            - --cluster-name={{ template "stolon.fullname" . }}
            - --store-backend={{ .Values.store.backend }}
            {{- if eq .Values.store.backend "kubernetes" }}
            - --kube-resource-kind={{ .Values.store.kubeResourceKind }}
            {{- else }}
            - --store-endpoints={{ .Values.store.endpoints }}
            {{- end }}
            - --yes
            - '{"initMode":"new"{{- if .Values.pgParameters }},"pgParameters":{{ with .Values.pgParameters }}{{ toJson . }}{{- end }}{{- end }}}'
{{ end }}

