#!/bin/sh

# this waits until an eventual $WAIT4DEB_URLS becomes present

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

if [ -z "${WAIT4DEB_URLS}" ] ; then
  echo "WARNING: WAIT4DEB_URLS empty, doing nothing."
  exit 0
fi
#export WAIT4DEB_URLS
NR_WAIT4DEB_URLS=$(echo ${WAIT4DEB_URLS} |wc -w |tr -d ' ')

echo "GOOD: Got ${NR_WAIT4DEB_URLS} WAIT4DEB_URLS set to check"

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

export SLEEPSECS=15
export ATTEMPTS=12

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."

export URLS_TO_CHECK=${WAIT4DEB_URLS}
export WAIT4DEB_URL=$(echo "${URLS_TO_CHECK}" |cut -f1 -d ' ')
export URLS_TO_CHECK=$(echo "${URLS_TO_CHECK} " |cut -f2- -d ' ')
export NR_URLS_REMAINING=$(echo "${URLS_TO_CHECK}" |wc -w |tr -d ' ')

while [ "${WGETRC}" != "0" -a "${I}" -lt ${ATTEMPTS} -a -n "${WAIT4DEB_URL}" ] ; 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} ..."
  WGETRC="0"
  while [ "${WGETRC}" = "0" -a -n "${WAIT4DEB_URL}" ] ; do
    echo "INFO: Checking ${WAIT4DEB_URL} ..." 
    wget --spider ${WAIT4DEB_URL} >/dev/null 2>/dev/null
    WGETRC="$?"
    if [ "${WGETRC}" = "0" ] ; then
      if [ "${NR_URLS_REMAINING}" = "0" ] ; then
        echo "GOOD: Successfully checked ${WAIT4DEB_URL}, this was the last URL."
        URLS_TO_CHECK="" # i.e. reduce from ' ' to ''
      else
        echo "GOOD: Successfully checked ${WAIT4DEB_URL}, ${NR_URLS_REMAINING} remaining."
      fi
      WAIT4DEB_URL=$(echo "${URLS_TO_CHECK}" |cut -f1 -d ' ')
      URLS_TO_CHECK=$(echo "${URLS_TO_CHECK}" |cut -f2- -d ' ') 
      NR_URLS_REMAINING=$(echo "${URLS_TO_CHECK}" |wc -w |tr -d ' ')
    else
      echo "WARNING: Failed to check ${WAIT4DEB_URL}"
    fi
  done
done

if [ "${WGETRC}" = "0" -a "${NR_URLS_REMAINING}" = "0" ] ; then
  echo "GOOD: Successfully checked availability of ${NR_WAIT4DEB_URLS} deb URLs"
  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 ${NR_WAIT4DEB_URLS} deb URLs."
echo "       Last exit code from wget on ${WAIT4DEB_URL} was ${WGETRC}."
echo "       After that there would be ${NR_URLS_REMAINING} remaining."
exit 1
