#!/bin/bash
#
# Wrapper to close properly redis and sentinel
#

test x"$REDIS_DEBUG" != x && set -x

REDIS_CLI=/usr/bin/redis-cli

# Retrieve service name
SERVICE_NAME="$1"
if [ -z "$SERVICE_NAME" ]; then
    SERVICE_NAME=default
fi

# Get the proper config file based on service name
CONFIG_FILE="/etc/redis/${SERVICE_NAME}.conf"

# Use awk to retrieve host, port, password from config file
HOST=`awk '/^[[:blank:]]*bind/ { print $2 }' $CONFIG_FILE`
PORT=`awk '/^[[:blank:]]*port/ { print $2 }' $CONFIG_FILE`
PASS=`awk '/^[[:blank:]]*requirepass/ { print $2 }' $CONFIG_FILE`

# Just in case, use default host, port
HOST=${HOST:-127.0.0.1}
if [ "$SERVICE_NAME" = "default" ]; then
    PORT=${PORT:-6379}
else
    PORT=${PORT:-26379}
fi

if [ -n "$PASS" ]; then
    PASS="-a $PASS"
else
    PASS=""
fi

# shutdown the service properly
$REDIS_CLI -h $HOST -p $PORT $PASS shutdown
