apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "redis-ha.fullname" . }}-probes
  labels:
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version }}
    app: {{ template "redis-ha.fullname" . }}
data:
  check-quorum.sh: |
    #!/bin/sh
    set -eu
    MASTER_GROUP="{{ .Values.redis.masterGroupName }}"
    SENTINEL_PORT={{ .Values.sentinel.port }}
    REDIS_PORT={{ .Values.redis.port }}
    NUM_SLAVES=$(redis-cli -p "$SENTINEL_PORT" sentinel master {{ .Values.redis.masterGroupName }} | awk '/num-slaves/{getline; print}')
    MIN_SLAVES={{ index .Values.redis.config "min-slaves-to-write" }}

    if [ "$1" = "$SENTINEL_PORT" ]; then
        if redis-cli -p "$SENTINEL_PORT" sentinel ckquorum "$MASTER_GROUP" | grep -q NOQUORUM ; then
            echo "ERROR: NOQUORUM. Sentinel quorum check failed, not enough sentinels found"
            exit 1
        fi
    elif [ "$1" = "$REDIS_PORT" ]; then
        if [ "$MIN_SLAVES" -gt "$NUM_SLAVES" ]; then
            echo "Could not find enough replicating slaves. Needed $MIN_SLAVES but found $NUM_SLAVES"
            exit 1
        fi
    fi
    sh /probes/readiness.sh "$1"

  readiness.sh: |
    #!/bin/sh
    set -eu
    CHECK_SERVER="$(redis-cli -p "$1"{{ if .Values.auth }} -a "$AUTH"{{ end }} ping)"

    if [ "$CHECK_SERVER" != "PONG" ]; then
        echo "Server check failed with: $CHECK_SERVER"
        exit 1
    fi
