#!/bin/csh -fx

#==============================================================================
#
#	Script to roll over the logs on NPAC web server.  This is designed to
#	run as root on clyde.  It must run as root because it has to kill off
#	and restart the HTTPd, bound to port 80.
#
#==============================================================================
#
#
#	Paths to files and directories
#
echo '['`date`'] Starting: rollover.sh'
set TEST = 0

set serverroot = /usr/local/servers/npac_http
set logroot = /e/p/C067
if ($TEST ) set logroot = /tmp/log_test                      # Test rollover.
set log_file = access_log
set ref_file = referer_log
set agt_file = agent_log
set logarch = $logroot/log_archive
set loghtml = /usr/local/archives/public/html/stats/archive
if ($TEST ) set loghtml = /tmp/log_test/html                 # Test rollover.
set wwwstat = /usr/local/servers/npac_http/tools/wwwstat-gang/wwwstat

#==============================================================================
#	You should not have to change anything below here.
#==============================================================================
#
#       Work out this year and this month
#	=================================
#
set thisyear = `date +%y`
set thismonth = `date +%b`  
set thisday = `date +%d`  
set thisdate = "$thisday/$thismonth/19$thisyear"
set thisdtg = `date +%y%m%d`

cd $logroot/logs
#
#	Stop HTTPd
#	==========
#
if ( $TEST == 0) then 
  echo "STOPPING HTTPD: `date`"
  if ( -f httpd.pid ) kill `cat httpd.pid`
endif

#
#	Loop over each log file and archive it
#	======================================
#
foreach log ( $log_file $ref_file $agt_file )
#
#	Make sure access log only contains this week.
#	  Remove todays hits from archive and save it.
#	  Remove today's hits from archive and put them back in the log file.
#	
#
  echo $log
  mv $log /tmp/log.$$
  grep -v "$thisdate" /tmp/log.$$ > $logarch/$log.$thisdtg
  grep "$thisdate" /tmp/log.$$ > $log
end

#
#	Keep last 1000 lines of error log and delete the rest.
#
mv error_log /tmp/error.$$
head -1000 /tmp/error.$$ > error_log
\rm -f /tmp/error.$$

#
#	Start the server
#	================
#
if ( $TEST == 0) then 
  echo "STARTING HTTPD: `date`"
  $serverroot/httpd -d $serverroot
endif

#
#	Update the list of unique agents
#	================================
#
cut -d']' -f,2, $logarch/agent_log.$thisdtg | \
   sed -e 's/ //' -e 's/via.*//' | sort -u > /tmp/agents.$$
if ( -f $loghtml/agents.txt ) then
  cat $loghtml/agents.txt >> /tmp/agents.$$
endif
sort -u /tmp/agents.$$ >! $loghtml/agents.txt
\rm -f /tmp/agents.$$
chmod 644 $loghtml/agents.txt
#
#	Compress log files
#	==================
#
foreach log (  $log_file $ref_file $agt_file )
  nice -9 gzip -9 $logarch/$log.$thisdtg
end

echo '['`date`'] Finished: rollover.sh'
exit
