#!/bin/bash

LOG_DIR="/data/acctlink/docker/app/logs"
LOG_FILE="$LOG_DIR/app.log"
BACKUP_DIR="$LOG_DIR/archive"
MAX_SIZE_MB=100  
MAX_DAYS=30     
COMPRESS_DAYS=1 
CONTAINER_NAME="acctlink-app-1"  

mkdir -p "$BACKUP_DIR" || { echo "Error: Cannot create backup directory"; exit 1; }
chmod 755 "$LOG_DIR" "$BACKUP_DIR"

if [ ! -f "$LOG_FILE" ]; then
    echo "Warning: Log file $LOG_FILE does not exist"
    exit 0
fi

current_size=$(du -m "$LOG_FILE" | cut -f1)

if [ "$current_size" -gt "$MAX_SIZE_MB" ]; then
    DATE=$(date +"%Y-%m-%d-%H%M%S")

    cp "$LOG_FILE" "$BACKUP_DIR/app.log.$DATE" || { echo "Error: Cannot copy log file"; exit 1; }

    chmod 644 "$BACKUP_DIR/app.log.$DATE"

    : > "$LOG_FILE" || { echo "Error: Cannot clear original log file"; exit 1; }

    find "$BACKUP_DIR" -name "app.log.*" -type f -mtime +$COMPRESS_DAYS -not -name "*.gz" -exec gzip {} \; || echo "Warning: Error compressing old logs"

    find "$BACKUP_DIR" -name "app.log.*.gz" -type f -mtime +$MAX_DAYS -delete || echo "Warning: Error deleting old logs"

    echo "Log rotation completed at $(date)"
    echo "Current log size: $(du -h "$LOG_FILE" | cut -f1)"
    echo "Total archived logs: $(find "$BACKUP_DIR" -type f | wc -l)"
    echo "Total archived size: $(du -sh "$BACKUP_DIR" | cut -f1)"
fi 