#!/bin/sh
# Shell script to try repeatedly to get files via ftp. The host
# is repeatedly polled until the session is successfully
# completed, or until the number of allowed tries is reached.

if [ "$#" -ne 2 ]
then
   echo "Usage: $0 hostName getList"
   exit 1
fi

# This is the site we're ftp'ing to.
host=$1

# Define the input, result and error files.
in=$2
out=$host.results
err=$host.errs

# How long to sleep between subsequent tries (in seconds):
time=300 # Five minutes
#time=120 # Two minutes
#time=60 # One minute

# How long to try (in seconds)
tryTime=1200 # 20 minutes
#tryTime=300 # 5 minutes
#tryTime=120 # 2 minutes
#tryTime=60 # 1 minute

# Number of loops allowed based on tryTime
numLoops=`expr $tryTime / $time`
loopCount=1

echo "Starting to get files from $host." > $out
# Try to make connection w/out error loop first time
# Initialize the error message file so we start the loop:
echo "Trying to reach $host at time:" >> $out
date +'%H:%M hrs; %d %h %y' >> $out
ftp $host < $in >> $out 2> $err

# MAIN LOOP: If error file isn't empty, we sleep for time and try again.
while test -s $err
do
   if [ "$loopCount" -ge "$numLoops" ]
   then
      echo "***Reached number of allowed loops ($numLoops)***" >> $out
      echo "***Exiting***" >> $out
      exit 1
   fi
   loopCount=`expr $loopCount + 1`

   echo "Cannot connect now, will try again in $time seconds." >> $out
   sleep $time

   echo "Trying to reach $host at time:" >> $out
   date +'%H:%M hrs; %d %h %y' >> $out
   ftp $host < $in >> $out 2> $err
done
echo "***Finished***" >> $out
