#!/bin/bash
#This script is used to process the redis-related configuration in the middleware file and the apm file in cluster mode.
#Cluster mode for v6 and greater only.

set -e

if [ -z ${1} ];then
    echo -e "[ERROR]. Please enter the compose file path.\n"
    echo -e "Example:\nsh redis_cluster_config.sh /opt\n"
    exit 11
fi

if [ ! -d ${1} ];then
    echo "${1} does not exist or not a file path."
    exit 11
fi

cp $(dirname "$PWD")/Template/docker-compose-mainregion.yml ${1}
cp $(dirname "$PWD")/Template/middleware-master-cluster.yml ${1}
cp $(dirname "$PWD")/Template/docker-compose-inbiz.yml ${1}
cp $(dirname "$PWD")/Template/docker-compose-apm-mainregion.yml ${1}
cp $(dirname "$PWD")/Template/docker-compose-clamav.yml ${1}
cp $(dirname "$PWD")/Template/docker-compose-fex.yml ${1}
cp $(dirname "$PWD")/Template/portainer-agent-stack.yml ${1}
cp $(dirname "$PWD")/Template/envfile.env ${1}

compose_dir=${1%*/}
sed -i -r '/^\s{2}+redis?./,/^$/{/entrypoint/ s/^#//g}' ${compose_dir}/middleware-master-cluster.yml
sed -i -r '/^\s{2}+redis?./,/^$/{/networks/ N;s/middleware/host/g}' ${compose_dir}/middleware-master-cluster.yml

for n in $(docker node ls |grep -v ID |awk '{print $1}');do
    for ((i=1; i<=3 ;i++));do
      if [ ! -z "$(docker inspect ${n} |grep "redis$i")" ];then
        ip=$(docker node inspect --format '{{if eq "0.0.0.0" .Status.Addr}}{{.ManagerStatus.Addr}}{{else}}{{.Status.Addr}}{{end}}' ${n}|awk -F':' '{print $1}')
        sed -i -r "/^### SVC:redis:>>>/,/^### SVC:redis:<<</{/extra_hosts/,/deploy/ s/^#//g;/extra_hosts/,/deploy/ {/redis${i}/ s/x/"${ip}"/g}}" ${compose_dir}/middleware-master-cluster.yml
        sed -i -r "/^### SVC:heartbeat:>>>/,/^### SVC:heartbeat:<<</{/extra_hosts/,/deploy/ s/^#//g;/extra_hosts/,/deploy/ {/redis${i}/ s/x/"${ip}"/g}}" ${compose_dir}/docker-compose-apm-mainregion.yml
        sed -i -r "/^### SVC:middleware:>>>/,/^### SVC:middleware:<<</{/extra_hosts/,/deploy/ s/^#//g;/extra_hosts/,/deploy/ {/redis${i}/ s/x/"${ip}"/g}}" ${compose_dir}/docker-compose-apm-mainregion.yml
        echo "RedisHostID${i}=${ip}" >> ${compose_dir}/envfile.env
      fi
    done
done

echo "The compose setup is complete."
echo "The compose is stored under the ${compose_dir} path."
