#!/bin/sh
#
# Verify the synchroniation of Redis Sentinel slaves.

output=$(mktemp --tmpdir $(basename "$0").XXXXXXXXXX)
critical_count=0
ok_count=0

trap "rm -f $output" EXIT

input=$(redis-cli -p 6380 sentinel slaves redis |  sed 'N;s/\n/=/')

#while read -r line; do 
for line in $input; do 
    case "$line" in
        name=*) name=${line#name=} ;;
        master-link-status=*) status=${line#master-link-status=} ;;
    esac 
    if [ -n "$name" ] && [ -n "$status" ]; then
        if [ "$status" = ok ]; then
            echo "OK - $name" >> "$output"
            ok_count=$(( ok_count + 1))
        else
            echo "CRITICAL - $name" >> "$output"
            critical_count=$(( critical_count + 1))
        fi
        unset name status
    fi
done

total_count=$(( ok_count + critical_count ))

plural=''
test "$total_count" -gt 1 && plural='s'

if [ $ok_count -eq  $total_count ]; then
     printf "OK - %d/%d  Redis Sentinel slave%s are in sync\n\n" \
         "$ok_count" "$total_count" "$plural"
     cat "$output"
     exit 0
else
    printf "CRITICAL - %d/%d Redis Sentinal slave%s aren't in sync\n\n" \
        "$critical_count" "$total_count" "$plural"
    cat "$output"
    exit 2 
fi
