#! /bin/csh
#
# tarraw - C shell script to tar raw mooring data into .tar.gz files
#	Note - this script then moves the raw files into directory
#	    ./raw/erase.  The intent is to allow ops/TSD folks to
#	    inspect the *.dir files to make sure everything is tar'd
#	    OK, and then erase the raw files from ./raw/erase.  It does
#	    this rather than rm'ing the files in order to allow recovery
#	    from script/system errors.
# This version has been modified so that it can be run after midnight,
# processing only the previous day's files. It takes jan 1 processing
# into account, correcting for leap years appropriately. ( 3/16/01 KLH)

# Copyright (C) 2001 MBARI
# Author: Kent Headley
# MBARI provides this documentation and code "as is", with no warranty,
# express or implied, of its quality or consistency. It is provided without
# support and without obligation on the part of the Monterey Bay Aquarium
# Research Institute to assist in its use, correction, modification, or
# enhancement. This information should not be published or distributed to
# third parties without specific written permission from MBARI.

set OASIS = /oasis
set TAR=$OASIS/raw/tar
set RAW=$OASIS/raw
set ERASE=$OASIS/raw/erase
set UNZIP=/usr/mbari/bin/gunzip
set ZIP=/usr/mbari/bin/gzip
set dllog = "dlinfo"
set nonomatch

cd $TAR

foreach mooring (m1 m2)

# Make a file list of YESTERDAY's files
# if TODAY is Jan 1, then check to see if last year was
# a leap year and assign YESTERDAY accordingly
 
@ today = `date +%j`
@ wrap = ($today == "001")

if ( $wrap == 1 ) then
	@ year = `date +%Y`
	@ year -= 1
	@ isleap = (($year % 4) == 0 && ($year % 100) != 0 || ($year % 400) == 0)

	if ($isleap == 1) then
		@ yesterday = (366)
	else
		@ yesterday = (365)
	endif
else
	@ yesterday = ($today - 1)
endif

#set filebase = `date +%Y``printf "%03d" $yesterday`
set filebase = `date +%Y``printf "%03d" $today`

if ( -e $mooring.tar.gz ) \
	$UNZIP $mooring.tar.gz >& /dev/null
	cd $RAW

    	set filelist = `ls $mooring.*|grep -v $filebase`
    	foreach file ($filelist)
    		tar rvf $TAR/$mooring.tar $file >& /dev/null
    		mv $file $ERASE
    	end

#	tar rvf tar/$mooring.tar $mooring.$filebase.* >& /dev/null
#	mv $mooring.$filebase.* $ERASE

	cd $TAR
	tar tvf $mooring.tar >& $mooring.dir
	$ZIP $mooring.tar >& /dev/null
end

cd $TAR
if ( !( -e $dllog.tar.gz ) ) then
	echo "Download Log Archive Created "`date` > log.start
	tar cvf $dllog.tar log.start
	$ZIP $dllog.tar
	rm -f log.start
endif

if ( -e $dllog.tar.gz ) then
	$UNZIP $dllog.tar.gz >& /dev/null
	cd $RAW
	set filebase = `date +%Y``printf "%03d" $today`
	set filelist = `ls $dllog.2*|grep -v $filebase`
	echo $filebase $filelist
	foreach file ($filelist)
		tar rvf $TAR/$dllog.tar $file >& /dev/null
		mv $file $ERASE
	end
	cd $TAR
	tar tvf $dllog.tar >& $dllog.dir
	$ZIP $dllog.tar >& /dev/null
endif
