#!/bin/sh
#
# use crond to run?
#
# logsize in blocks (typically 1024) above which we rotate
redundancy_mode=`uci get misc.log.redundancy_mode`

if [ "$redundancy_mode" = "1" ]; then
	LOG_SIZE=$((3*1024*1024))
	TMP_LOG_SIZE=$((1024*1024))
	# how many compressed generations to keep
	LOGGEN=5
else
	LOG_SIZE=$((256*1024))
	TMP_LOG_SIZE=$((100*1024))
	# how many compressed generations to keep
	LOGGEN=5
	MIN_AVAIL_SIZE=85
fi

# logfile
TMP_LOG=/tmp/messages
LOG=/data/usr/log/messages
WIFI_LOG_TMP=/tmp/wifi_analysis.log
WIFI_LOG=/data/usr/log/wifi_analysis.log

mkdir -p /data/usr/log
touch $WIFI_LOG_TMP

#
export LANG=C
#
. /lib/lib.scripthelper.sh
#
#run in daemon
#procdaemon mute
#
dlog "INFO: syslog-ng helper."
#

while true
do

sleep 120

if [ "$redundancy_mode" != "1" ]; then
	# check available space in /data
	if [ `df -h /data | awk '{print $5}' | grep -v Use | awk -F '%' '{print $1}'` -gt $MIN_AVAIL_SIZE ]; then
		dlog "Available space in /data is too small, so we should delete log files."
		rm -rf /data/usr/log/*
	fi
fi

# check if we are ready to rotate
if [[ `stat -c%s $TMP_LOG` -lt $TMP_LOG_SIZE  ]] && [ `stat -c%s $WIFI_LOG_TMP` -lt $TMP_LOG_SIZE ] && ( [[ ! -f $LOG  ]] || [[ `stat -c%s $LOG` -lt $LOG_SIZE  ]] ); then
# too small - skip this time
continue
fi

#Save wifi log to /data/log
if [ `stat -c%s $WIFI_LOG_TMP` -gt $TMP_LOG_SIZE ]; then
        cp $WIFI_LOG_TMP $WIFI_LOG_TMP.0
        > $WIFI_LOG_TMP
        gzip $WIFI_LOG_TMP.0
        mv $WIFI_LOG_TMP.0.gz $WIFI_LOG.0.gz
fi


if [ "$redundancy_mode" = "1" ]; then
	cat $TMP_LOG >> $LOG
	sync
	> $TMP_LOG

        # check if we are ready to rotate
        if [ `stat -c%s $LOG` -lt $LOG_SIZE  ]; then
                # too small - skip this time
                continue
        fi
fi

# we need to do the rotation
i=$LOGGEN
while [ $i -gt 0 ]; do
	# rotate one step
	newer=$(($i-1))
	# check if we need to compress
	if [ -f $LOG.$newer.gz ]; then
		# already compressed - just rotate
		mv $LOG.$newer.gz $LOG.$i.gz
	elif [ -f $LOG.$newer ]; then
		# need to compress
		mv $LOG.$newer $LOG.$i
		gzip $LOG.$i
	fi
	# next do the previous generation
	i=$(($i-1))
done

if [ "$redundancy_mode" = "1" ]; then
	# rotate the current file
	mv $LOG $LOG.0
	dlog "INFO: rotate $LOG => $LOG.0"
else
	# rotate the current file
	mv $TMP_LOG $TMP_LOG.0
	gzip $TMP_LOG.0

	# check if we are ready to rotate
	if [ `stat -c%s $TMP_LOG.0.gz` -lt $LOG_SIZE ]; then
	# rotate
	mv $TMP_LOG.0.gz $LOG.0.gz
	fi
fi

# kick syslog-ng to start a new file
killall -HUP syslog-ng 2>/dev/null
#
done
