#!/bin/bash

##################################################
# Docker                                         #
# - --privileged                                 #
# Mount dir                                      #
# - LOG_DIR                                      #
# - DATA_DIR                                     #
# ENV                                            #
# - _CONF_*                                      #
# - MASTER_NODES                                 #
# - SLAVE_NODES                                  #
##################################################

set -euo pipefail
export LANG=en_US.UTF-8
trap Quit EXIT

PIDS=
GOT_SIGTERM=
LOG_DIR='/var/log/redis'
DATA_DIR='/var/lib/redis'
SOCK_FILE='/run/redis/redis.sock'
MASTER_NODES=(${MASTER_NODES:-})
SLAVE_NODES=(${SLAVE_NODES:-})
DEPLOY_CLUSTER=
CLUSTER_CONFIG_FILE="$DATA_DIR/nodes.conf"
REQUIREPASS=

function Print {
    local file=/dev/null
    [ '-f' = "$1" ] && file=$2 && shift && shift
    date +"[%F %T] $*" | tee -a $file
}

function Quit {
    local errCode=$?
    Print Killing redis-server ...
    [ -f $SOCK_FILE ] \
        && redis-cli ${REQUIREPASS:+-a $REQUIREPASS --no-auth-warning} \
            -s $SOCK_FILE shutdown \
        || true
    while :; do
        pkill -f redis-server && Print Killing redis-server ... || break
        sleep 1
    done
    [ 100 -eq $errCode ] && rm -f $CLUSTER_CONFIG_FILE
    Print Container stopped.
    test -n "$GOT_SIGTERM"
}

function ModifyConf {
    local kv=
    local clusterEnabled=
    [ -e /etc/redis.conf ] && Print /etc/redis.conf already exists. && return 0
    Print Modifying conf ...
    echo "bind 0.0.0.0
protected-mode no
maxmemory 6442450944
maxmemory-policy volatile-random
timeout 300
maxclients 8192
" > /etc/redis.conf
    while read kv; do
        [ 'cluster-enabled=yes' == "$kv" ] && clusterEnabled=1
        [[ "$kv" =~ ^requirepass= ]] && REQUIREPASS=${kv#*=}
        echo "${kv/=/ }" >> /etc/redis.conf
    done <<< "$(env | grep '^_CONF_' | sed 's/_CONF_//')"
    [ -e "$CLUSTER_CONFIG_FILE" -o -z "$clusterEnabled" -o -z "${MASTER_NODES[*]}" ] \
        || DEPLOY_CLUSTER=1
}

function DeployCluster {
    Print Deploying redis cluster ...
    local i=
    local node=
    local nodesId=
    local clusterInfo=
    local redisCliCmd="redis-cli ${REQUIREPASS:+-a $REQUIREPASS --no-auth-warning}"
    [ 0 -ne ${#SLAVE_NODES[@]} -a ${#SLAVE_NODES[@]} -ne ${#MASTER_NODES[@]} ] \
        && Print The num of slave nodes not equal to the num of master nodes! \
        && exit 100
    Print Checking the state of all nodes ...
    for node in ${MASTER_NODES[@]} ${SLAVE_NODES[@]}; do
        for i in {0..5}; do
            [ 5 -eq $i ] \
                && Print Failed to connect to $node! \
                && exit 100
            sleep 2
            clusterInfo=$($redisCliCmd -h ${node/:/ -p } info cluster) || continue
            echo "$clusterInfo" | grep -q cluster_enabled:1 && break
            Print $node not enable cluster mode! && exit 100
        done
    done
    Print Creating redis cluster with master nodes: ${MASTER_NODES[@]}
    $redisCliCmd --cluster-yes --cluster create ${MASTER_NODES[@]}
    nodesId="$($redisCliCmd -s $SOCK_FILE cluster nodes | cut -d@ -f1)"
    for i in ${!SLAVE_NODES[@]}; do
        Print Adding slave node ${SLAVE_NODES[$i]} with master: ${MASTER_NODES[$i]}
        $redisCliCmd --cluster-yes --cluster add-node ${SLAVE_NODES[$i]} \
            ${MASTER_NODES[0]} --cluster-slave \
            --cluster-master-id $(echo "$nodesId" \
                | grep "${MASTER_NODES[$i]}$" \
                | awk '{print $1}')
    done
}

function Init {
    echo 1024 > /proc/sys/net/core/somaxconn \
        && echo 1 > /proc/sys/vm/overcommit_memory \
        || Print Not specified "--privileged".
    mkdir -p $LOG_DIR $DATA_DIR
}

function StartProc {
    Print Starting Redis ...
    redis-server /etc/redis.conf \
        --daemonize no \
        --dir $DATA_DIR \
        --cluster-config-file $CLUSTER_CONFIG_FILE \
        --logfile $LOG_DIR/redis.log \
        --unixsocket $SOCK_FILE &
    PIDS="$PIDS $!"
    while sleep 1; do
        [ -e $SOCK_FILE ] && break || echo -n .
        [ ! -e /proc/$! ] && echo && Print Unexpected error! && exit
    done
    echo
    [ -n "$DEPLOY_CLUSTER" ] && DeployCluster
    Print Redis is ready for connections.
}

function Main {
    local pid=
    ModifyConf
    Init
    StartProc
    trap "GOT_SIGTERM=1; Print Got SIGTERM ..." SIGTERM
    while [ -z "$GOT_SIGTERM" ] && sleep 2; do
        for pid in $PIDS; do
            [ ! -e /proc/$pid ] && Print Unexpected error! && exit
        done
    done
}

# Start here
Main

