#!/bin/sh

# Run terracotta's Disk Garbage Collector on the cluster's active node.

# Use terracotta's server-stat script to get the local host's current
# role (ACTIVE or PASSIVE).  Only run the Disk Garbage Collector on
# the active node.

# This script is designed to be run by a cron job on each terracotta server
# and so whether active or passive, the DGC will be run as appropriate.

prog=$0

echo "$prog starting at $(date)"
# Make sure JAVA_HOME is set appropriately.
if [ -z "$JAVA_HOME" ]; then
    export JAVA_HOME=/usr/java/latest
    echo setting JAVA_HOME=$JAVA_HOME
else
    echo using JAVA_HOME=$JAVA_HOME
fi

# Set the terracotta directory as needed.
if [ -z "$TC_INSTALL_DIR" ]; then
    export TC_INSTALL_DIR=/usr/local/terracotta
    echo setting TC_INSTALL_DIR=$TC_INSTALL_DIR
else
    echo using TC_INSTALL_DIR=$TC_INSTALL_DIR
fi

localhost_role=$($TC_INSTALL_DIR/bin/server-stat.sh | awk '/^localhost.role/ { print $2; }')
echo "localhost's role is ${localhost_role}"
case ${localhost_role} in
  ACTIVE)
    echo "role is active, running dgc..."
    $TC_INSTALL_DIR/bin/run-dgc.sh
    ;;
  PASSIVE)
    echo "role is passive, skipping dgc"
    ;;
  *)
    echo "unknown role ${localhost_role}, NOT running dgc"
    ;;
esac

echo "$prog ending at $(date)"
