#!/bin/sh
set -eu

debci_base_dir=$(readlink -f "$(dirname "$(readlink -f "${0}")")/..")
. "${debci_base_dir}/lib/environment.sh"
. "${debci_base_dir}/lib/functions.sh"

# shellcheck disable=SC2154
mkdir -p "${debci_results_dir}"

shutdown() {
  if [ -n "${inotifywait}" ]; then
    kill "${inotifywait}"
  fi
}
trap shutdown INT TERM EXIT

while true; do
  inotifywait -qq "${debci_results_dir}" --include '.*\.stamp' &
  inotifywait=$!
  wait $inotifywait
  inotifywait=

  for f in "${debci_results_dir}"/*.stamp; do
    results="${f%%.stamp}.tar.gz"
    exitcode="$(tar taf "${results}" | grep '/exitcode$' || true)"
    if [ -z "${exitcode}" ]; then
      log "W: cannot extract data from ${results}; ignoring"
      continue
    fi
    suite="$(echo "$exitcode" | cut -d / -f 2)"
    arch="$(echo "$exitcode" | cut -d / -f 3)"
    package="$(echo "$exitcode" | cut -d / -f 5)"
    filename="$(basename "${results}" .tar.gz)"
    run_id="$(echo "${filename}" | cut -d . -f 1)"
    backend="$(echo "${filename}" | cut -d . -f 2)"
    log "${package} ${suite}/${arch}/${backend} (${run_id}) publishing"
    # shellcheck disable=SC2154 disable=SC2086
    if retry --times=3 --delay=5 -- amqp-publish \
      --url="${debci_amqp_server}" \
      $debci_amqp_tools_options \
      --persistent \
      --routing-key="${debci_amqp_results_queue}" < "${results}"
    then
      log "${package} ${suite}/${arch}/${backend} (${run_id}) published"
      rm -f "${f}" "${results}"
    else
      log_error "E: failed to publish $(basename "${results}"). Will try again later"
    fi
  done
done
