#!/bin/bash
if [ -f /usr/local/nginx/conf/nginx.conf ]; then
mkdir mkdir -p /backup/rclone_backup/nginx_access_log/
touch /backup/nginx_access_log

if [ ! -L /usr/local/nginx/on ] && [ -f /usr/local/nginx/on ]
then
	mv /usr/local/nginx/on /usr/local/nginx/first_on
	gzip /usr/local/nginx/first_on 
	mv /usr/local/nginx/first_on.gz /backup/rclone_backup/nginx_access_log/
else 
	rm -rf /usr/local/nginx/on
	ln -s  /backup/nginx_access_log /usr/local/nginx/on
fi



mkdir -p /usr/local/drsrv/
cat > "/usr/local/drsrv/access_log.sh" <<-'EOF'
#!/bin/bash


if [ ! -f /backup/nginx_access_log ]
then
	touch /backup/nginx_access_log
	service nginx restart
fi
if [ ! -L /usr/local/nginx/on ]
then
	rm -rf /usr/local/nginx/on
	ln -s  /backup/nginx_access_log /usr/local/nginx/on
	service nginx restart
fi

logsize=$(stat --printf="%s"  /backup/nginx_access_log)
if [ "$logsize" -gt "20480000000"  ] 
then
	nginx_access_log=nginx_access_log_`hostname`_`date +"%F_%H_%m"`.log
	mv /backup/nginx_access_log  /backup/${nginx_access_log}
	rm -rf /backup/nginx_access_log
	touch /backup/nginx_access_log
	service nginx restart
	gzip  /backup/${nginx_access_log}
	mkdir -p /backup/rclone_backup/nginx_access_log/
	mv /backup/${nginx_access_log}.* /backup/rclone_backup/nginx_access_log/
fi 
EOF

cp /usr/local/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf_`date +'%H_%M'`
rm -rf /usr/local/nginx/conf/nginx_new.conf

sed -i '/log_format/d' /usr/local/nginx/conf/nginx.conf
sed -i '/access_log/d' /usr/local/nginx/conf/nginx.conf

while read line
do 
echo "$line"
if [[ "$line" = 'http {' ]] 
then 
curl https://www.drsrv.com/scripts/log_format.txt
fi
done < /usr/local/nginx/conf/nginx.conf > /usr/local/nginx/conf/nginx_new.conf && rm -rf /usr/local/nginx/conf/nginx.conf && mv /usr/local/nginx/conf/nginx_new.conf /usr/local/nginx/conf/nginx.conf
chmod a+x /usr/local/drsrv/access_log.sh

sed -i '/access_log.sh/d' /var/spool/cron/root
echo "10 * * * * sh /usr/local/drsrv/access_log.sh" >> /var/spool/cron/root

service nginx restart 
service crond reload 
fi 