#!/bin/bash set -euo pipefail # Get the server's hostname and derive the client name HOSTNAME=$(hostname) CLIENT_NAME=${HOSTNAME%.[MYCOMPANYDOMAIN]} # Define the base S3 bucket path S3_BUCKET="s3://[MYBUCKETNAME]" PREFIX="$S3_BUCKET/ServerBackups/$CLIENT_NAME/" # Sync PBX backup files (quiet, recursive) s3cmd sync --recursive --quiet /var/lib/vitalpbx/backup/* "$PREFIX" # Delete remote files older than 7 days (top-level only) echo "Checking for files older than 7 days in $PREFIX ..." LATEST_FILE=$(s3cmd ls "$PREFIX" | sort -k1,2 | tail -n 1 | awk '{print $4}') s3cmd ls "$PREFIX" | while IFS= read -r line; do # Only process broadband file lines [[ "$line" =~ ^20[0-9]{2}-[0-9]{2}-[0-9]{2}\ ]] || continue CREATE_DATE=$(echo "$line" | awk '{print $1" "$2}') FILE=$(echo "$line" | awk '{print $4}') # Skip deletion if this is the most recent file if [[ "$FILE" == "$LATEST_FILE" ]]; then continue fi CREATE_TS=$(date -d "$CREATE_DATE" +%s) NOW_TS=$(date +%s) AGE=$(( (NOW_TS - CREATE_TS) / 86400 )) if (( AGE > 7 )); then s3cmd del --force --quiet "$FILE" fi done