#!/bin/sh

# Consume completed jobs from the AMQP queue

set -eu

short_options='c:'
long_options='count:,do-request'

usage() {
  cat <<EOF
usage: debci-drain [OPTIONS]

Options:
  -c COUNT, --count COUNT   Exit after processing COUNT requests. Default: 100

$@
EOF
}

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

# Process one request. Read the AMQP message from stdin.
do_request() {

  read -r request || true  # we expect EOF and thus read to fail
  # shellcheck disable=SC2086
  set -- $request
  if [ $# -eq 0 ]; then
    return
  fi

  # shellcheck disable=SC2068
  for param in $@; do
    case "$param" in
      run-id:*)
        arg=${param#run-id:}
        run_id="${arg}"
        break
        ;;
      *)
        :
        ;;
    esac
  done

  if job_is_completed "${run_id}"; then
    log "Job ${run_id} is marked as complete at the server, ignoring"
    return
  fi

  log "Job ${run_id} still pending, giving it back"
  exit 1
}


# parse CLI arguments
count=100
while true; do
  case "$1" in
    -c|--count)
      count="$2"
      shift 2
      ;;
    --do-request)
      do_request
      exit 0
      ;;
    *)
      break
      ;;
  esac
done


# if the user calls this, we run forever with consuming messages;
# amqp-consume calls ourselves with the (hidden) --do-request option
amqp_queue="$(debci amqp print-queue --arch="${debci_arch}" --backend="${debci_backend}")"
log "I: Connecting to AMQP queue $amqp_queue on ${debci_amqp_server_display}"
debci amqp declare-queue --arch="${debci_arch}" --backend="${debci_backend}"
exec amqp-consume \
  --url "${debci_amqp_server}" \
  "$debci_amqp_tools_options" \
  --queue="$amqp_queue" \
  --prefetch-count="${count}" --count="${count}" \
  -- \
  "$0" --do-request --arch="${debci_arch}" --backend="${debci_backend}"
