#!/bin/bash
# Log Cleanup Script
# Deletes logs older than 30 days

LOG_DIR="/var/www/html/homoeopathy/logs"
DAYS_TO_KEEP=30

echo "[$(date)] Starting log cleanup..." >> "$LOG_DIR/cleanup.log"

# Delete rotated logs older than 30 days
find "$LOG_DIR" -name "*.log.*.gz" -mtime +$DAYS_TO_KEEP -delete
find "$LOG_DIR" -name "*.log.*.bak" -mtime +$DAYS_TO_KEEP -delete

# Compress current logs if they exceed 10MB
for log in errors.log access.log ai.log cron.log; do
    LOG_FILE="$LOG_DIR/$log"
    if [ -f "$LOG_FILE" ]; then
        SIZE=$(stat -c%s "$LOG_FILE")
        if [ $SIZE -gt $((10 * 1024 * 1024)) ]; then
            TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
            mv "$LOG_FILE" "$LOG_FILE.$TIMESTAMP"
            gzip "$LOG_FILE.$TIMESTAMP"
            touch "$LOG_FILE"
            echo "[$(date)] Rotated $log (was $SIZE bytes)" >> "$LOG_DIR/cleanup.log"
        fi
    fi
done

echo "[$(date)] Log cleanup completed" >> "$LOG_DIR/cleanup.log"