#! /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

[ $# = 1 ] || { echo "Usage: remove_site_from_cassandra <site ID to remove>" >&2 ; exit 2 ; }

REMOTE_SITE=$1

echo "Removing a site from Cassandra..."

# 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 remove the site"
    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 NODE in $(echo "select * from system.peers;" | $CQLSH | grep $REMOTE_SITE | tr -d ' ' | cut -d'|' -f 3)
do
  /usr/share/clearwater/bin/run-in-signaling-namespace nodetool removenode $NODE
done
