#!/bin/bash
# Set some vars
perfdata_dir='/usr/local/nagios/share/perfdata'
cutoff_days=5

echo 'WARNING: This script will delete all RRDs (and their respective XML files) under /usr/local/nagios/share/perfdata'
echo '         that have not been written to in 5 days, that also includes hosts/services that have been DOWN for more'
echo '         than 5 days, please be aware of that limitation.'
echo
echo '         Please take an XI backup and/or a filesystem level backup first, just in case, see here for more information:'
echo
echo '         https://assets.nagios.com/downloads/nagiosxi/docs/Backing-Up-And-Restoring-Nagios-XI.pdf'
echo
read -r -p "Are you sure you want to continue? [y/N] " ok

case "$ok" in
    Y | y ) :
        echo 'Starting Deletion'
        # Get a list of RRDs that haven't had mtime updated in $cutoff_days
        rrd_array=($(find $perfdata_dir -type f -name "*.rrd" -mtime +$cutoff_days))

        # Loop through and delete all .rrd and .xml files
        for i in "${rrd_array[@]}"; do
            # Ignore .pnp-internal directory
            if [[ $i == *".pnp-internal"* ]]; then
                continue;
            fi

            # Do the deletion of RRD and XML files
            echo "Deleting: $i"
            \rm -f "$i"
            echo "Deleting: ${i/rrd/xml}"
            \rm -f "${i/rrd/xml}"
        done
        echo "Done"
        exit 0
        ;;
    * )     exit 1
esac