# Configuration
count=4
clustername=mycluster
admin=admin
password=password

networkname=couchbase
volumename=couchbase

# inside the pods, do not change it
volumepath=/opt/couchbase/var

# create a network
podman network create ${networkname}

# and now create $count servers, decay ports
for i in $(seq $count); do
    port1=$((8091 + (i-1)*4 ))
    port2=$((8094 + (i-1)*4 ))
    podman pod create --name server$i --network ${networkname} -p $port1-$port2:8091-8094
    podman volume create ${volumename}${i}
    podman run -d --rm --name couch$i --pod server$i -v ${volumename}${i}:${volumepath} docker.io/couchbase:community
done

# wait for the server 1 to respond
echo "Waiting for the first server to be up and running..."
RESPOND=0
until [ $RESPOND == 1 ]; do
    podman exec -t couch1 bash -c 'curl -sf server1:8091 -o /dev/null' && RESPOND=1
done

# now, init the cluster
podman exec -it couch1 couchbase-cli cluster-init \
    --cluster-name=${clustername} --cluster-username=${admin} --cluster-password=${password} \
    --services fts,data,index,query

# add others server to the cluster
for i in $(seq 2 $count); do
    RESPOND=0
    echo "Waiting server $i to be up and running..."
    until [ $RESPOND == 1 ]; do
        podman exec -t couch1 bash -c 'curl -sf server'${i}':8091 -o /dev/null' && RESPOND=1
    done
    podman exec -it couch$i bash -c 'couchbase-cli server-add -c server1 -u '${admin}' -p '${password}' \
        --server-add $(hostname -I) --server-add-username '${admin}' --server-add-password '${password}
done

# and rebalance
podman exec -it couch1 couchbase-cli rebalance -u ${admin} -p ${password} -c server1


echo
echo "CouchBase cluster accessible at http://localhost:8091"
echo 
echo To remove all:
cat  <<EOF
for i in {1..$count}; do
    podman pod rm -f server\${i}
    podman volume rm ${volumename}\${i}
done
podman network rm ${networkname}
EOF