#!/bin/bash
#
# cleanup-old-backups.sh - Remove backups older than retention period
#
# Deletes backup files older than 7 days while preserving the 'latest' symlinks
#

set -euo pipefail

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKUP_ROOT="$(dirname "$SCRIPT_DIR")"
STORAGE_DIR="$BACKUP_ROOT/storage"
LOG_FILE="$BACKUP_ROOT/logs/backup.log"

# Retention period in days
RETENTION_DAYS=7

# Logging function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] [CLEANUP] $1" | tee -a "$LOG_FILE"
}

log "Starting cleanup of backups older than $RETENTION_DAYS days..."

# Track cleanup statistics
TOTAL_DELETED=0
TOTAL_SIZE_FREED=0

# Clean up each backup type
for backup_type in database files crontab; do
    TYPE_DIR="$STORAGE_DIR/$backup_type"

    if [[ ! -d "$TYPE_DIR" ]]; then
        log "Skipping $backup_type - directory does not exist"
        continue
    fi

    # Find and delete old backup files (not symlinks)
    # Use -mtime for modification time older than retention period
    DELETED_COUNT=0
    DELETED_SIZE=0

    while IFS= read -r -d '' file; do
        # Skip symlinks (like 'latest')
        if [[ -L "$file" ]]; then
            continue
        fi

        # Get file size before deletion
        FILE_SIZE=$(stat -f%z "$file" 2>/dev/null || stat -c%s "$file" 2>/dev/null || echo 0)

        # Delete the file
        if rm -f "$file"; then
            ((DELETED_COUNT++))
            ((DELETED_SIZE += FILE_SIZE))
            log "Deleted: $file"
        else
            log "WARNING: Failed to delete: $file"
        fi
    done < <(find "$TYPE_DIR" -type f -mtime +${RETENTION_DAYS} -print0 2>/dev/null)

    if [[ $DELETED_COUNT -gt 0 ]]; then
        log "Cleaned up $DELETED_COUNT $backup_type backup(s)"
        ((TOTAL_DELETED += DELETED_COUNT))
        ((TOTAL_SIZE_FREED += DELETED_SIZE))
    fi
done

# Clean up old log entries (keep 30 days of logs)
LOG_DIR="$BACKUP_ROOT/logs"
if [[ -d "$LOG_DIR" ]]; then
    OLD_LOG_COUNT=0
    while IFS= read -r -d '' logfile; do
        if rm -f "$logfile"; then
            ((OLD_LOG_COUNT++))
        fi
    done < <(find "$LOG_DIR" -type f -name "*.log.*" -mtime +30 -print0 2>/dev/null)

    if [[ $OLD_LOG_COUNT -gt 0 ]]; then
        log "Cleaned up $OLD_LOG_COUNT old log file(s)"
    fi
fi

# Convert bytes to human readable
if [[ $TOTAL_SIZE_FREED -gt 0 ]]; then
    if [[ $TOTAL_SIZE_FREED -gt 1073741824 ]]; then
        SIZE_HUMAN="$(echo "scale=2; $TOTAL_SIZE_FREED / 1073741824" | bc)GB"
    elif [[ $TOTAL_SIZE_FREED -gt 1048576 ]]; then
        SIZE_HUMAN="$(echo "scale=2; $TOTAL_SIZE_FREED / 1048576" | bc)MB"
    elif [[ $TOTAL_SIZE_FREED -gt 1024 ]]; then
        SIZE_HUMAN="$(echo "scale=2; $TOTAL_SIZE_FREED / 1024" | bc)KB"
    else
        SIZE_HUMAN="${TOTAL_SIZE_FREED}B"
    fi
    log "Cleanup completed: $TOTAL_DELETED file(s) deleted, $SIZE_HUMAN freed"
else
    log "Cleanup completed: No old backups to remove"
fi

exit 0
