#!/bin/bash
set -eu
set -o pipefail

NUMBER_OF_ATTEMPTS=3

if [[ -z "${AUTOBUILD_ROOT:-}" ]]; then
  function log() { echo "$*" >&2; }
else
  . "$AUTOBUILD_ROOT/lib/log.sh"
fi

PERL_SCRIPT="$(dirname "$(realpath "$0")")/deptrace-make-db.pl"
OUTPUT="${1:-deptrace-db.txt}"
CODENAME="${2:-$(source /etc/os-release || source /usr/lib/os-release; echo $VERSION_CODENAME)}"

function _download() {
  local url="http://archive.ubuntu.com/ubuntu/dists/${1}/Contents-amd64.gz"
  log "downloading $url"
  curl --location --fail --no-progress-meter "$url"
}

function _write() {
  log "processing package data"
  perl "$PERL_SCRIPT" > "$OUTPUT"
  log "written deptrace database to $OUTPUT"
}

for i in $(seq 1 $NUMBER_OF_ATTEMPTS); do
  if (
    (
      _download "${CODENAME}-updates"
      _download "${CODENAME}"
    ) | zcat | _write
  ); then
    exit 0
  else
    log "attempt $i/$NUMBER_OF_ATTEMPTS failed"
    [ $i != $NUMBER_OF_ATTEMPTS ] && sleep 2
  fi
done
exit 1
