#!/bin/sh

set -eu

service=cassandra

echo "Start service"
systemctl start ${service}

echo "Check if the service is active"
if ! systemctl is-active -q ${service}; then
    echo "FAILURE: The service is not active"
    systemctl status ${service}
    exit 1
fi

echo "Wait for service to be ready, be patient..."
sleep 80s

echo "Print service logs"
systemctl status ${service} -n 500

echo "Print cqlsh version"
cqlsh -v

# XXX The python driver prints deprecation warnings on stderr.
# Please drop the '2>/dev/null' when cassandra is updated to 5.x
echo "Execute statement 'HELP' via cqlsh"
cqlsh -e HELP 2>/dev/null

echo "Check that the status is Up/Normal (UN)"
status=$(nodetool status)
if ! echo "$status" | sed '1,/^-- *Address/ d' | grep -q ^UN; then
    echo "FAILURE: Status is not Up/Normal (UN), see below:"
    echo "--------"; echo "$status"; echo "--------"
    exit 1
fi

echo "Stop service"
systemctl stop ${service}

echo "Check if the service active"
if systemctl is-active -q ${service}; then
    echo "FAILURE: The service is still active"
    systemctl status ${service}
    exit 1
fi
