#!/bin/sh

# this waits until an eventual $WAIT4DEB_URL becomes present

# optional parameters: [sleepSecs [attempts]]
# defaulting to 15 resp. 12

if [ -z "${WAIT4DEB_URL}" ] ; then
  echo "WARNING: WAIT4DEB_URL empty, doing nothing."
  exit 0
fi

echo "INFO: WAIT4DEB_URL set to ${WAIT4DEB_URL}"

# 15 seconds sleeps
# ~ 3 minutes
# = 12 attempts

export SLEEPSECS=15
if [ -n "$1" ] ; then
  SLEEPSECS="$1"
  shift
fi

export ATTEMPTS=12
if [ -n "$1" ] ; then
  ATTEMPTS="$1"
  shift
fi

if [ -n "$1" ] ; then
  SLEEPSECS="$1"
  shift
  echo "INFO: Using ${SLEEPSECS} sleepSecs, as specified as \$1." 
else
  echo "INFO: No sleepSecs specified as \$1, using default sleepSecs ${SLEEPSECS}." 
fi

if [ -n "$1" ] ; then
  ATTEMPTS="$1"
  shift
  echo "INFO: Using ${ATTEMPTS} attempts, as specified as \$2." 
else
  echo "INFO: No attempts specified as \$2, using default attempts ${ATTEMPTS}." 
fi

I=0
WGETRC="-1"

echo "INFO: Giving PBA supply chain time first, 1 sleep cylce of ${SLEEPSECS} seconds."

while [ "${WGETRC}" != "0" -a "$I" -lt ${ATTEMPTS} ] ; do
  # raise I, with ((I += 1)) not working in sh
  I=$(expr $I + 1)
  # first attempt after 1 sleep cycle
  echo "INFO: Sleeping a bit ..."
  sleep ${SLEEPSECS}
  # attempt
  echo "INFO: Attempt $I of up to ${ATTEMPTS} ..."
  wget --spider ${WAIT4DEB_URL}
  WGETRC="$?"
  #echo "INFO: Done attempt $I ..."
done

if [ "${WGETRC}" = "0" ] ; then
  echo "GOOD: Successfully checked availability of ${WAIT4DEB_URL}"
  echo "INFO: Giving archive a few more secs to complete meta data work."
  sleep 3
  exit 0
fi

echo "ERROR: Giving up on availability of ${WAIT4DEB_URL}"
exit 1
