#!/bin/bash

sargStDir=/var/www/html/squid
sargStArhDir=/mnt/arhiv/arhives/arh_proxy
curDT=`date +%s`
arhDT=$[curDT-2*30*24*60*60]

# Scan monthly directory for get old archives
for imonth in `ls -1t ${sargStDir}/monthly | sed -n '/\(.*-.*\)/s//\1/p'`; do
    if test `stat -c %Y ${sargStDir}/monthly/$imonth` -lt $arhDT; then
	wYear=`echo $imonth | sed -n '/\([0-9]\{4\}\).*-.*/s//\1/p'`
	wMonth=`echo $imonth | sed -n '/[0-9]\{4\}\(.\{3\}\).*-.*/s//\1/p'`

	echo "Statistic '${wYear}${wMonth}' process..."

	# Move archive directories to pack place
	# Monthly
	for idir in `ls -1t ${sargStDir}/monthly | sed -n "/\(${wYear}${wMonth}.*\)/s//\1/p"`; do
	    mv ${sargStDir}/monthly/$idir $sargStArhDir/monthly/
	done
	cp -r ${sargStDir}/monthly/images $sargStArhDir/monthly/
	sed "s/\(^.*class=\"data2\".*${wYear}${wMonth}.*\$\)/ \1/" ${sargStDir}/monthly/index.html | sed '/^[^ ].*class="data2"/d' > $sargStArhDir/monthly/index.html

	# Weekly
	for idir in `ls -1t ${sargStDir}/weekly | sed -n "/\(${wYear}${wMonth}.*\)/s//\1/p"`; do
	    mv ${sargStDir}/weekly/$idir $sargStArhDir/weekly/
	done
	cp -r ${sargStDir}/weekly/images $sargStArhDir/weekly/
	sed "s/\(^.*class=\"data2\".*${wYear}${wMonth}.*\$\)/ \1/" ${sargStDir}/weekly/index.html | sed '/^[^ ].*class="data2"/d' > $sargStArhDir/weekly/index.html

	# Daily
	for idir in `ls -1t ${sargStDir}/daily | sed -n "/\(${wYear}${wMonth}.*\)/s//\1/p"`; do
	    mv ${sargStDir}/daily/$idir $sargStArhDir/daily/
	done
	cp -r ${sargStDir}/daily/images $sargStArhDir/daily/
	sed "s/\(^.*class=\"data2\".*${wYear}${wMonth}.*\$\)/ \1/" ${sargStDir}/daily/index.html | sed '/^[^ ].*class="data2"/d' > $sargStArhDir/daily/index.html

	# Pack month directories
	cd $sargStArhDir
	tar cjf ${wYear}${wMonth}.tar.bz2 monthly weekly daily

	# Free month directories
	rm -rf monthly/* weekly/* daily/*
    fi
done