#!/bin/sh

LOG_DIR="/tmp/logs"
CURRENT_LOG="$LOG_DIR/console_output.log"
MAX_FILES=30
#MAX_SIZE=1048576 # 1MB in bytes
#MAX_SIZE=524288 # 512KB in bytes
#MAX_SIZE=131072 # 128KB in bytes
MAX_SIZE=10240 # 10KB in bytes

#mkdir -p "$LOG_DIR"
#exec 1>>"$CURRENT_LOG"
#exec 2>>"$CURRENT_LOG"

# Rotate logs
rotate_logs() {
    if [ -f "$CURRENT_LOG" ] && [ "$(wc -c < "$CURRENT_LOG")" -ge "$MAX_SIZE" ]; then
        TIMESTAMP=$(date +%Y%m%d_%H%M%S)
        ROTATED_LOG="$LOG_DIR/console_$TIMESTAMP.log"

        # Copy the current log to a rotated log file
        cp "$CURRENT_LOG" "$ROTATED_LOG"
#        echo "Rotated log to $ROTATED_LOG"

        # Clear the current log file without breaking its file descriptor
        : > "$CURRENT_LOG"
    fi
}

# Delete old logs
delete_old_logs() {
    LOG_COUNT=$(ls -1 "$LOG_DIR"/*.log 2>/dev/null | wc -l)
    if [ "$LOG_COUNT" -gt "$MAX_FILES" ]; then
        OLDEST_FILE=$(ls -1t "$LOG_DIR"/*.log | tail -n 1)
        rm -f "$OLDEST_FILE"
#        echo "Deleted old log file: $OLDEST_FILE"
    fi
}

delete_trtc_logs() {
    rm /tmp/web/trtc_log/* -rf
}

while true; do
    rotate_logs
    delete_old_logs
    delete_trtc_logs
    sleep 600 # 10 minute
done
