#!/bin/bash
#This script used to cut nginx logs and compress logs during the first day of a month.
#Add crond: 0 0 * * * root /bin/bash /cut_log.sh
#Powered by:    sndapk
#date:      20130913
PATH=/bin:/usr/bin:/sbin:/usr/sbin
export PATH
log_path=/var/log/nginx
log_name="access.log"
nginx_pid=`ps aux | grep 'nginx: master' | grep -v 'grep nginx' | awk '{print $2}'`
last_day=`date -d yesterday +%Y%m%d`
last_month=`date -d yesterday +%Y%m`
compress_day=`date +%d`
save_days=31
#cut logs every day.
for log_dir in `ls $log_path`
do
    cd $log_path/$log_dir &&
    if [ -f $log_name ];then
        mv $log_name $last_day"_"$log_name
        kill -USR1 $nginx_pid
    fi
done
#compress logs every month.
if [ $compress_day -eq 01 ];then
    for log_dir in `ls $log_path`
    do
        cd $log_path/$log_dir &&
        mkdir $last_month &&
        mv $last_month[0-3][0-9]* $last_month
        tar -zcf $last_month.tgz $last_month && rm -rf $last_month
    done
fi
#delete $save_days ago file.
find $log_path -type f -mtime +$save_days -exec rm -f {} \;