#! /bin/bash

# Copyright (C) Metaswitch Networks
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.

cassandra_hostname="127.0.0.1"

. /etc/clearwater/config
. /usr/share/clearwater/utils/check-root-permissions 1
. /usr/share/clearwater/cassandra_schema_utils.sh

quit_if_no_cassandra

echo "Updating Cassandra's replication strategy..."

# Wait for the cassandra cluster to come online
count=0
/usr/share/clearwater/bin/poll_cassandra.sh --no-grace-period > /dev/null 2>&1

while [ $? -ne 0 ]; do
  ((count++))
  if [ $count -gt 120 ]; then
    echo "Cassandra isn't responsive, unable to update the replication strategy"
    exit 1
  fi

 sleep 1
  /usr/share/clearwater/bin/poll_cassandra.sh --no-grace-period > /dev/null 2>&1

done

CQLSH="/usr/share/clearwater/bin/run-in-signaling-namespace cqlsh $cassandra_hostname"

for KEYSPACE in $(ls /var/lib/cassandra/data/ 2>/dev/null)
do
  if [ $KEYSPACE != "system" ] && [ $KEYSPACE != "system_traces" ]; then
    echo "Updating the replication strategy for $KEYSPACE"
    echo "ALTER KEYSPACE $KEYSPACE WITH REPLICATION =  $replication_str;" | $CQLSH
  fi
done
