#! /bin/csh -f

# Ships current .phase, .cnss files to NCEDC at frequency specified
# in crontabs, though the name implies every hour

# Written by David Oppenheimer - 2/13/98

set path=(. ~/bin /local/ssh/bin /usr/local /usr/ucb /bin /local/bin /usr/bin /usr/lang /usr/hosts /local/Datacenter/dcmgr/bin )

set online_dir = /local/Datacenter/online
set phase_dir = /local/Datacenter/data/phase 
cd $online_dir

# set date variables

set long_date = `date -u`
set Yr = $long_date[6]
set Mo = `date -u +%m`
set mrg_out = $Yr.$Mo.phase
set cnss_sum = NC.$Yr.$Mo.cnss

# check to see if this process is already running

if (-e LOCKFILE.hourly) then
  echo "LOCKFILE exists - exiting" > errmsg.hourly
  echo `ps -e | grep ppicker` >> errmsg.hourly
  echo `date` >> errmsg.hourly
  echo `ls -l LOCKFILE.hourly` >> errmsg.hourly
  goto cleanup
else
  cp nullfile LOCKFILE.hourly
endif

# retrieve phase file

if (-e "$phase_dir"/$Yr/$mrg_out.Z) then
  cp "$phase_dir"/$Yr/$mrg_out.Z hourly.phase.Z
else
  echo "No data exists for today in $phase_dir/$Yr/$mrg_out.Z - exiting" > errmsg.hourly
  goto cleanup
endif
if (-z hourly.phase.Z) then
  echo "hour.phase.Z is zero length" > errmsg.hourly
  goto cleanup
endif

# scp and mv phase file

scp -q hourly.phase.Z oppen@quake.geo.berkeley.edu:/home/ftp/dc/tmp.cat/$mrg_out.Z >& /dev/null
ssh -l oppen quake.geo.berkeley.edu mv /home/ftp/dc/tmp.cat/$mrg_out.Z /home/ftp/dc/import.cat/$mrg_out.Z >& /dev/null

# generate cnss data

uncompress hourly.phase
egrep '^1|^2' hourly.phase >! j.sum
eqselect -poly \
34.5 -121.25 37.43 -117.76 39. -120. 42. -120. 42. -122.7 43. -125. 43. -126. 40. -126. 34.5 -121.25 \
j.sum >! $Yr.$Mo.sum
extract -e $Yr.$Mo.sum hourly.phase >! hourly_poly.phase
ncsn2cnss < hourly_poly.phase >! $cnss_sum
compress -f $cnss_sum
scp -q $cnss_sum.Z oppen@quake.geo.berkeley.edu:/home/ftp/dc/tmp.cnss/$cnss_sum.Z >& /dev/null
ssh -l oppen quake.geo.berkeley.edu mv /home/ftp/dc/tmp.cnss/$cnss_sum.Z /home/ftp/dc/import.cnss/$cnss_sum.Z >& /dev/null

cleanup:
if ( -e errmsg.hourly) then
  mail -s "HOURLY.CSH exiting" oppen@usgs.gov, macbeth@usgs.gov, dietz@usgs.gov <errmsg.hourly
  /bin/rm -f errmsg.hourly 
endif

/bin/rm -f LOCKFILE.hourly hourly.phase $cnss_sum.Z $Yr.$Mo.sum hourly_poly.phase

exit
