From ef2bb4f28ab87fd6cefd2f174104d71fffd37b12 Mon Sep 17 00:00:00 2001 From: Tristan Ancelet Date: Thu, 6 Jun 2024 17:15:31 -0500 Subject: [PATCH] Added new handle_logs function --- do-daily-btrfs-snapshot.sh | 58 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/do-daily-btrfs-snapshot.sh b/do-daily-btrfs-snapshot.sh index be853a7..7b17870 100755 --- a/do-daily-btrfs-snapshot.sh +++ b/do-daily-btrfs-snapshot.sh @@ -50,8 +50,56 @@ DATE_REGEX='[0-9]{4}-[0-9]{2}-[0-9]{2}' # END: Variables + +# BEGIN: Helper Functions + +function handle_logs() { + cd $LOG_DIR + echo "Began Handling logs at: $(date)" + local ARCHIVE_FILE=archive.tar.gz + local ARCHIVE_FILE_UNZIPED=${ARCHIVE_FILE%.gz} + + if [[ -f $ARCHIVE_FILE ]]; then + ## Decompressing archive in case it exists + gunzip $ARCHIVE_FILE 2>/dev/null + fi + + ## Getting all files + local FILES=( $( ls -1tr *.log ) ) + if [[ ${#FILES[@]} -le $LIMIT ]]; then + echo "Only had ${#FILES[@]} logs, and did not exceed $LIMIT. Not handling logs" + return + fi + + ## Getting files we are keeping + local FILES_TO_KEEP=${FILES[@]: -$LIMIT} + + ## Creating REGEX filter + FILES_TO_KEEP=${FILES_TO_KEEP//[[:space:]]/|} + + ## Filtering out logs to keep + local FILES_TO_ARCHIVE=( $( ls -1 *.log | grep -Ev "(${FILES_TO_KEEP})" ) ) + + echo "Adding archived logs to archive" + ## Updating archive + tar uvf $ARCHIVE_FILE_UNZIPED ${FILES_TO_ARCHIVE[@]} + + ## Compressing Archive + echo "Compressing Archive" + gzip $ARCHIVE_FILE_UNZIPED + + ## Removing archived logs + echo "Removing archived files" + rm -vf ${FILES_TO_ARCHIVE[@]} + echo "Finished Handling logs at: $(date)" + +} + +# END: Helper Functions + # BEGIN: Pre-Work Checks +## Setting up the script to direct all output to the log file for this snapshot session exec > $LOG_FILE ## This will check to make sure that the log directory has been created, if not it will create it @@ -60,7 +108,6 @@ exec > $LOG_FILE echo "$LOG_DIR did not exist. Creating" } -## Setting up the script to direct all output to the log file for this snapshot session # END: Pre-Work Checks @@ -104,8 +151,15 @@ for SUBVOL_INFO in ${SUBVOLS[@]}; do SNAPSHOT=$SUBVOL_BACKUP_DIR/$DATE ## If the snapshot doesn't already exist, then create a new read-only snapshot - [[ ! -d $SNAPSHOT ]] && /usr/sbin/btrfs subvol snapshot -r $DIR $SNAPSHOT + if [[ ! -d $SNAPSHOT ]]; then + /usr/sbin/btrfs subvol snapshot -r $DIR $SNAPSHOT + else + echo "$SNAPSHOT already existed. Not backing up" + fi done +handle_logs + echo "Finishing backup at `date`" + # END: Work