From 37efa2b2c63ee67d7159740bd0ebb48d3cde562a Mon Sep 17 00:00:00 2001 From: Philipp Dreimann Date: Sun, 2 Nov 2025 15:43:16 +0100 Subject: [PATCH] introduce a new option: backup --delete-oldest, which deletes the N oldest backups, and keeps the last complete backup. --- helper-scripts/backup_and_restore.sh | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/helper-scripts/backup_and_restore.sh b/helper-scripts/backup_and_restore.sh index e665ad403..6164331a7 100755 --- a/helper-scripts/backup_and_restore.sh +++ b/helper-scripts/backup_and_restore.sh @@ -11,8 +11,8 @@ if [[ ! ${1} =~ (backup|restore) ]]; then exit 1 fi -if [[ ${1} == "backup" && ! ${2} =~ (crypt|vmail|redis|rspamd|postfix|mysql|all|--delete-days) ]]; then - echo "Second parameter needs to be 'vmail', 'crypt', 'redis', 'rspamd', 'postfix', 'mysql', 'all' or '--delete-days'" +if [[ ${1} == "backup" && ! ${2} =~ (crypt|vmail|redis|rspamd|postfix|mysql|all|--delete-days|--delete-oldest) ]]; then + echo "Second parameter needs to be 'vmail', 'crypt', 'redis', 'rspamd', 'postfix', 'mysql', 'all', '--delete-days' or '--delete-oldest'" exit 1 fi @@ -221,6 +221,23 @@ function backup() { echo "Parameter of --delete-days is not a number." fi ;; + --delete-oldest) + shift + if [[ "${1}" =~ ^[0-9]+$ ]]; then + TOTAL=$(find ${BACKUP_LOCATION}/mailcow-* -maxdepth 0 -type d 2>/dev/null | wc -l) + if [[ ${TOTAL} -eq 0 ]]; then + echo "No backups found to delete." + elif [[ ${TOTAL} -eq 1 ]]; then + echo "Only 1 backup exists, keeping it (minimum 1 backup required)." + else + TO_DELETE=$((${1} < ${TOTAL} ? ${1} : ${TOTAL} - 1)) + echo "Found ${TOTAL} backups, deleting ${TO_DELETE} oldest (keeping at least 1)." + find ${BACKUP_LOCATION}/mailcow-* -maxdepth 0 -type d -printf '%T+ %p\n' | sort | head -n ${TO_DELETE} | cut -d' ' -f2- | xargs -r rm -rvf + fi + else + echo "Parameter of --delete-oldest is not a number." + fi + ;; esac shift done