#!/bin/bash
set -e

echo "===== Starting rrdcached test ====="

TEST_RRD="/var/lib/rrdcached/db/cachedtest.rrd"
SOCK="/run/rrdcached.sock"

# Clean up previous runs
rm -f "$TEST_RRD"

# start socket
echo "--> rrdcached socket should be enabled"
systemctl status rrdcached.socket
systemctl is-enabled rrdcached.socket
systemctl is-active rrdcached.socket

echo "--> rrdcached service should not be active now"
if systemctl is-active rrdcached.service; then
    echo 'rrdcached.service should not be active'
    exit 1
fi
if systemctl is-enabled rrdcached.service; then
    echo 'rrdcached.service should not be enabled'
    exit 1
fi

# Create an RRD file for testing
echo "--> Creating RRD file..."
rrdtool create "$TEST_RRD" \
    --start now-10m --step 60 \
    --daemon "unix:$SOCK" \
    DS:test:GAUGE:120:0:100 \
    RRA:AVERAGE:0.5:1:10
echo "OK: RRD file created."

# Update via daemon
echo "--> Updating RRD via daemon..."
rrdtool update --daemon "unix:$SOCK" "$TEST_RRD" N:50
echo "OK: Update command sent to daemon."

# Flush data to disk
echo "--> Flushing data..."
rrdtool flushcached --daemon "unix:$SOCK" "$TEST_RRD"
echo "OK: Flush command sent."

# now the service should be active
echo "--> Check service being active now"
systemctl is-active rrdcached.service

echo "===== rrdcached test PASSED ====="
exit 0
