#!/bin/bash
# Third-party, see oss-summary/src/tools/ftp-posting-tool/README.md
# Copyright (c) 2014-2015 Spotify AB
# Copyright 2019-2019 The Last Pickle Ltd
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

REAPER_JAR=$(find /usr/share/cassandra-reaper -maxdepth 4 -regex '.*/cassandra-reaper-.*[0-9rT]\.jar')

if [ $REAPER_JAR ]; then
    echo "Using reaper in target"
    CLASS_PATH=$REAPER_JAR
fi

if [ -z "$CLASS_PATH" ]; then
  echo "Looking for reaper in /usr/local/share/"
  CLASS_PATH="$(find /usr/local/share -maxdepth 4  -regex '.*/cassandra-reaper-.*[0-9rT]\.jar'):$(find /usr/share -regex '.*/cassandra-reaper-.*[0-9rT]\.jar')"
fi

if [ $# -eq 0 ]; then
    if [ -e /usr/local/etc/cassandra-reaper/cassandra-reaper.yaml ]; then
        CONFIG_PATH="/usr/local/etc/cassandra-reaper/cassandra-reaper.yaml"
    else
        CONFIG_PATH="/etc/cassandra-reaper/cassandra-reaper.yaml"
    fi
else
    CONFIG_PATH="$@"
fi

JVM_OPTS=(
    # it is safe and performant to disable assertions in production environments (ie replace `-ea` with `-da`)
    -da
    -Xmx2G
    -XX:+ExitOnOutOfMemoryError
    # Prefer binding to IPv4 network intefaces (when net.ipv6.bindv6only=1). See
    # http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6342561 (short version:
    # comment out this entry to enable IPv6 support).
    -Djava.net.preferIPv4Stack=true
    )

exec java ${JVM_OPTS[@]} \
    -cp ${CLASS_PATH} \
    io.cassandrareaper.ReaperApplication \
    server ${CONFIG_PATH}
