#!/bin/bash

# @file cassandra
#
# Copyright (C) Metaswitch Networks 2016
# 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.

. /etc/clearwater/config

TEMPLATE_HEAPSIZE_SECTION=""

TEMPLATE_FILE=/usr/share/clearwater/cassandra/cassandra-env.sh.template
new_file=$(mktemp)

# On AIO nodes and in containers, we want to restrict Cassandra's memory usage,
# as the system is shared with more processes, and Cassandra's approach of
# using 70% of RAM isn't appropriate.

if [[ $reduce_cassandra_mem_usage = "Y" ]]
then
  TEMPLATE_HEAPSIZE_SECTION="MAX_HEAP_SIZE=\"512M\"\nHEAP_NEWSIZE=\"128M\""
fi

cat $TEMPLATE_FILE |\
  sed "s/<<<TEMPLATE_HEAPSIZE_SECTION>>>/$TEMPLATE_HEAPSIZE_SECTION/"\
  > $new_file

if [[ -e /etc/cassandra/cassandra-env.sh &&
  "$(md5sum < /etc/cassandra/cassandra-env.sh)" = "$(md5sum < $new_file)" ]]
then
  # File unchanged, do nothing
  /bin/true
else
  rm -f /etc/cassandra/cassandra-env.sh
  cp $new_file /etc/cassandra/cassandra-env.sh
  # File has changed, need to restart cassandra to pick up the change.
  service cassandra stop
fi

chmod 0755 /etc/cassandra/cassandra-env.sh
rm $new_file
