#!/bin/bash

# get the MAX_DISK_USE and LOG_DIR settings
source /etc/conf.d/log_packets
LOG_DIR="${LOGDIR}/${HOSTNAME}/dailylogs"


get_cur_use() {
	df -P ${LOG_DIR} | grep -v -i filesystem | awk '{print $5}' | tr -d %
}

# This func checks the current space being used by LOG_DIR
# and rm's data as necessary.
cleandisk() {

        echo "Checking disk space (limited to ${MAX_DISK_USE}%)..."
        CUR_USE=$(get_cur_use)
        echo "  Current Disk Use: ${CUR_USE}%"
        
        while [ ${CUR_USE} -gt ${MAX_DISK_USE} ]
        do
                # If we are here then we passed our disk limit
                # First find the oldest DIR
                cd "${LOG_DIR}"
                # Can't use -t on the ls since the mod time changes each time we
                # delete a file. Good thing we use YYYY-MM-DD so we can sort.
                OLDEST_DIR=$(ls | grep -v today | sort | head -n 1)
                if [ -z "${OLDEST_DIR}" ]
                then
                	echo "no more files to clean. Giving up."
                	exit
                fi
                cd "${OLDEST_DIR}"

                OLDEST_FILE=$(ls -t | tail -n 1)

                if [ -f "${OLDEST_FILE}" ]
                then
                        echo "  Removing file: ${OLDEST_DIR}/${OLDEST_FILE}"
                        rm -f "${OLDEST_FILE}"
                else
                        echo "  Removing empty dir: ${OLDEST_DIR}"
                        cd ..
                        rm -rf "${OLDEST_DIR}"
                fi
                
                # Run cleandisk again as rm'ing one file might no have been enough
                sync
                echo "  Waiting 1 secs for disk to sync..."
                sleep 1
        done
        echo "Done."
}


# restart all running log_packets@ units
#
# when started by the log_packets_clean.timer unit, this
# runs on 00:00 every day, so that the new instance
# will log to a new subdirectory with the current date.
#
UNITS_RUNNING=$(/usr/bin/systemctl list-units "log_packets@*" \
	        --all --no-legend --no-pager \
		| awk '{ print $1 }')
[ ! -z "${UNITS_RUNNING}" ] \
	&& /usr/bin/systemctl try-restart ${UNITS_RUNNING}

# now cleanup old files, if needed
cleandisk
