#!/bin/bash
#
# Backup folders maintenance operation planned at once a day.
# This script called usually by the cron (but indirectly).
# Uses the rotate_folder utility which must be available on path.
#
# Author: Kovács Zoltán <kovacsz@marcusconsulting.hu>
# License: GNU/GPL v3+ (https://www.gnu.org/licenses/gpl-3.0.en.html)
# 2025-05-20 v0.1 Initial release

# Will maintain child subfolders of this directory.
# Input parameter (if any) will be sanitized later.
[[ -n "$1" ]] \
&& BACKUPSROOT="$1" \
|| BACKUPSROOT="$PWD"
	
# Checks the components.
[[ -z "$(which dirname)"  ]] && exit 1
[[ -z "$(which readlink)" ]] && exit 1
[[ -z "$(which xargs)"    ]] && exit 1

# Where I'm?
SCRPATH="$( cd -P "$( "$(which dirname)" "$0" )" && echo "$PWD" )"

# Rotates the backup folders.
#
# Enumerates the folders and tries to rotate they content.
for folder in $(ls -1 "$BACKUPSROOT" 2>/dev/null | $(which xargs) -0 ) ""
do
    if [ -n "$folder" ]; then
	# Dereferenced absolute path.
	folder="$("$(which readlink)" -e "$BACKUPSROOT/$folder")" #"
	# Does it a folder with a prepared configuration?
	if [ -d "$folder" -a -r "$folder/.rotate_folder.conf" ]; then
    	    # Does the rotate job.
    	    if [ -x "$SCRPATH/rotate_folder" ]; then
		"$SCRPATH/rotate_folder" -f "$folder" >/dev/null
    	    elif [ -x "$(which rotate_folder)" ]; then
		"$(which rotate_folder)" -f "$folder" >/dev/null
    	    fi
	fi
    fi
done
#
# Done with rotating.

# That's all, Folks :)
