#!/bin/bash
# compress-laravel-logs.sh
# Compresses laravel daily log files older than 1 day into laravel-logs/ folder.
# Safety: only removes .log after verifying .gz exists and is non-empty.
# Never deletes any .gz file from laravel-logs/.
# Runs via daily cron.

LOGS_DIR="/home/centralgoparts/public_html/storage/logs"
ARCHIVE_DIR="${LOGS_DIR}/laravel-logs"

# Ensure archive dir exists
mkdir -p "$ARCHIVE_DIR"

# Find laravel-YYYY-MM-DD.log files older than 1 day
find "$LOGS_DIR" -maxdepth 1 -name "laravel-*.log" -mtime +0 -type f | while read logfile; do
    filename=$(basename "$logfile")
    gzfile="${ARCHIVE_DIR}/${filename}.gz"

    # Skip if already compressed
    if [ -f "$gzfile" ]; then
        echo "[SKIP] ${filename} - already compressed in archive"
        # If .gz already exists and is valid, remove the .log
        if [ -s "$gzfile" ]; then
            rm -f "$logfile"
            echo "[CLEANUP] Removed ${filename} (archive already exists)"
        fi
        continue
    fi

    # Compress to archive
    echo "[COMPRESS] ${filename} ..."
    gzip -c "$logfile" > "$gzfile"

    # Verify: .gz must exist and be non-empty
    if [ -f "$gzfile" ] && [ -s "$gzfile" ]; then
        rm -f "$logfile"
        echo "[DONE] ${filename} -> ${gzfile} ($(du -h "$gzfile" | cut -f1))"
    else
        echo "[ERROR] Compression failed for ${filename} - keeping original"
        rm -f "$gzfile"
    fi
done

echo "[$(date '+%Y-%m-%d %H:%M:%S')] Compression run complete."
