#!/bin/bash

realpath() {
    [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
}

thiscript=`readlink $0`
if [ $? -ne 0 ]; then
    thiscript=$0
fi

HERE=`dirname ${thiscript}`
if [ ${HERE} = "/" ]; then
    echo "Please do not install redis-stack to /"
    exit 3
fi

if [ ${HERE} = "." ]; then
BASEDIR=..
else
BASEDIR=`dirname $HERE`
fi

# default database location
REDIS_DATA_DIR=`pwd`

if [ -d /opt/redis-stack ]; then
    _datadir=/var/lib/redis-stack
elif [ -d /opt/homebrew/var ]; then
    BREW_BASE=/opt/homebrew
    _datadir=/opt/homebrew/var/db/redis-stack
elif [ -d /usr/local/var ]; then
    BREW_BASE=/usr/local
    _datadir=/usr/local/var/db/redis-stack
else
   BREW_BASE=${BASEDIR}
   _datadir=${BASEDIR}/var/db/redis-stack
fi
mkdir -p ${_datadir}
touch ${_datadir}/.testfile 2>&1
if [ $? -eq 0 ]; then
    REDIS_DATA_DIR=${_datadir}
fi


CMD=${BASEDIR}/bin/redis-server
if [ -f "${1}" ]; then
    CONFFILE="${1}"
    shift
elif [ -f ${BASEDIR}/etc/redis-stack.conf ]; then
    CONFFILE=${BASEDIR}/etc/redis-stack.conf
elif [ -f ${BREW_BASE}/etc/redis-stack.conf ]; then
    CONFFILE=${BREW_BASE}/etc/redis-stack.conf
fi
MODULEDIR=$(realpath ${BASEDIR})/lib

if [ -z ${REDISEARCH_ARGS} ]; then
REDISEARCH_ARGS="MAXSEARCHRESULTS 10000 MAXAGGREGATERESULTS 10000"
fi

echo "Starting redis-stack-server, database path ${REDIS_DATA_DIR}"

${CMD} \
${CONFFILE} \
--dir ${REDIS_DATA_DIR} \
--protected-mode no \
--daemonize no \
--loadmodule ${MODULEDIR}/rediscompat.so \
--loadmodule ${MODULEDIR}/redisearch.so ${REDISEARCH_ARGS} \
--loadmodule ${MODULEDIR}/redistimeseries.so ${REDISTIMESERIES_ARGS} \
--loadmodule ${MODULEDIR}/rejson.so ${REDISJSON_ARGS} \
--loadmodule ${MODULEDIR}/redisbloom.so ${REDISBLOOM_ARGS} \
--loadmodule ${MODULEDIR}/redisgears.so v8-plugin-path ${MODULEDIR}/libredisgears_v8_plugin.so  ${REDISGEARS_ARGS} \
$*
