#!/bin/bash

# @file memcached
#
# 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

# On an IPv6 system memcached need to be configured to listen on the hostname
# that maps to the local IP address.
listen_address=$local_ip

if /usr/share/clearwater/bin/is-address-ipv6 $local_ip
then
  listen_address=$(/usr/share/clearwater/bin/ipv6-to-hostname $local_ip)
fi

. /usr/share/clearwater/utils/cassandra_enabled

if [ "$USE_CASSANDRA" == "Y" ];
then
  # If Cassandra is in use, then only use 256 MB per core
  cache=$(($(grep processor /proc/cpuinfo | wc -l) * 256000000))
else
  # Otherwise, use 1.5 GB per core
  cache=$(($(grep processor /proc/cpuinfo | wc -l) * 1536000000))
fi

# Each line of this command modifies the config as follows:
# - Sets the listen address to the signaling IP address of this node.
# - Sets ignore_vbucket to true
# - Sets a cache size limit, based on the spec of the machine, and
#   whether Cassandra is in use.
# - Return errors on exhaustion rather than dropping old data
# - Enables the first level of verbose logging.
# - Enables core dumps.
# - Sets the limit on the number of simultaneous connections to 4096.
sed -e 's/^-l .*$/-l '$listen_address'/g'\
    -e "s/^-m .*$/-e ignore_vbucket=true;cache_size=$cache;eviction=false/g"\
    -e 's/^# *-v *$/-v/g'\
    -e 's/^# *-r *$/-r/g'\
    -e 's/^\(# *\|\)-c.*$/-c 4096/g' </etc/memcached.conf >/etc/memcached_11211.conf

printf "\n# Disable listening on UDP\n-U 0\n" >> /etc/memcached_11211.conf

echo "START_PREFIX=/usr/share/clearwater/bin/run-in-signaling-namespace" > /etc/default/memcached
