#!/bin/sh

set -x

cd $DATA

#################################
# Sleep until dump is complete on ncosp
#################################
dorcp=no
try=0
while [ $try -lt $ntrymax ]
do
   /etc/ping $REMOTE_HOST 64 2
   pingerr=$?
   if [ $pingerr -eq 0 ]
   then
     dorcp=YES
     try=$ntrymax
   else
     msg="Cannot Contact $REMOTE_HOST on try $try of $ntrymax"
     postmsg "$jlogfile" "$msg"
     let try=try+1 
   fi
done

if [ $NET = "hur" -o $RUN = "sst" -o $RUN = "mrf" -o $NET = "hourly" ] ; then
   echo " no file to copy."
elif [ $dorcp = "YES" ] ; then
  where_file=$REMOTE_DIR/where_${cycle}_${REMOTE_RUN}_${scp_type}_ran
  cnt=0
  dumpdone=1
  while [ $dumpdone -ne 0 ]; do
     scp ${REMOTE_HOST}:${where_file} .
     if [ $cnt -ge 60 ] ; then
      err_exit "Giving up after waiting 30 minutes for ${NET} ${scp_type} to complete on ${REMOTE_HOST}"
     fi
     if [ -s where_${cycle}_${REMOTE_RUN}_${scp_type}_ran ]; then      
        dumpdone=0 
     else
       sleep 30
      let cnt=cnt+1
     fi
  done
else
  err_exit "Cannot Contact $REMOTE_HOST after $ntrymax try/tries"
fi

#################################
# Define Fix File with File List to scp
#################################
filelist=$FIXutil/scp_$FIXFILE

try=0
doscp=NO

while [ $try -lt $ntrymax ]
do
   /etc/ping $REMOTE_HOST 64 2
   pingerr=$?
   if [ $pingerr -eq 0 ]
   then
     doscp=YES
     try=$ntrymax
   else
     msg="Cannot Contact $REMOTE_HOST on try $try of $ntrymax"
     postmsg "$jlogfile" "$msg"
     let try=try+1 
   fi
done

sed "s/CYCLE/$cycle/" ${filelist} >> tmpscp

if test "$doscp" = "YES"
then
   for file in `cat tmpscp` 
      do
      scp ${REMOTE_HOST}:${REMOTE_DIR}/${file} ${LOCAL_DIR}/
   done
else
   err_exit "Cannot Contact $REMOTE_HOST after $ntrymax try/tries"
fi

chgrp rstprod ${LOCAL_DIR}/*sfcshp*bufr_d 
chgrp rstprod ${LOCAL_DIR}/*sfcshp*bufr_d.listing 
chgrp rstprod ${LOCAL_DIR}/*aircar.tm*.bufr_d 
chgrp rstprod ${LOCAL_DIR}/*aircar.tm*.bufr_d.listing
chgrp rstprod ${LOCAL_DIR}/*adpsfc*bufr_d 
chgrp rstprod ${LOCAL_DIR}/*adpsfc*bufr_d.listing 
chgrp rstprod ${LOCAL_DIR}/*aircft*bufr_d
chgrp rstprod ${LOCAL_DIR}/*aircft*bufr_d.listing
chgrp rstprod ${LOCAL_DIR}/*msonet*bufr_d 
chgrp rstprod ${LOCAL_DIR}/*msonet*bufr_d.listing 
chgrp rstprod ${LOCAL_DIR}/*prepbufr*pre-qc
chgrp rstprod ${LOCAL_DIR}/*prepbufr*pre-qc.tm00
chgrp rstprod ${LOCAL_DIR}/*prepbufr
chgrp rstprod ${LOCAL_DIR}/*prepbufr.tm00
chgrp rstprod ${LOCAL_DIR}/*prepbufr.unblok
chgrp rstprod ${LOCAL_DIR}/*.sdm*
chgrp rstprod ${LOCAL_DIR}/*cnvstat*

exit
