#!/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 where file ftped."
elif [ $dorcp = "YES" ] ; then
  where_file=$REMOTE_DIR/where_${cycle}_${REMOTE_RUN}_${ftp_type}_ran
  cnt=0
  dumpdone=1
  while [ $dumpdone -ne 0 ] ; do
cat << EOF > ftpin
  prompt
  bin
  cd $REMOTE_DIR
  get where_${cycle}_${REMOTE_RUN}_${ftp_type}_ran
  bye
EOF
    ftp -v $REMOTE_HOST < $DATA/ftpin
    if [ $cnt -ge 60 ] ; then
      err_exit "Giving up after waiting 30 minutes for ${NET} ${ftp_type} to complete on ${REMOTE_HOST}"
    fi
    if [ -s where_${cycle}_${REMOTE_RUN}_${ftp_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 ftp
#################################
filelist=$FIXutil/ftp_$FIXFILE

cat << EOF > ftpin
  lcd $LOCAL_DIR
  cd $REMOTE_DIR
  prompt
  bin
EOF

sed 's/^.*/mget &/' $filelist >> tmpftp
sed "s/CYCLE/$cycle/" tmpftp >> ftpin
rm -rf tmpftp

cat << EOF >> ftpin
  bye
EOF

try=0
doftp=NO

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

if test "$doftp" = "YES"
then
   ftp -v $REMOTE_HOST < $DATA/ftpin
else
   err_exit "Cannot Contact $REMOTE_HOST after $ntrymax try/tries"
fi

exit
