#!/bin/sh

case $- in
  *i*)
    ;;
  *)
    set -eu
    ;;
esac

autopkgtest_dir_for_package() {
  local pkg="$1"
  pkg_dir=$(echo "$pkg" | sed -e 's/\(\(lib\)\?.\).*/\1\/&/')
  echo "${debci_autopkgtest_dir}/${pkg_dir}"
}

autopkgtest_incoming_dir_for_package() {
  local pkg="$1"
  pkg_dir=$(echo "$pkg" | sed -e 's/\(\(lib\)\?.\).*/\1\/&/')
  echo "${debci_autopkgtest_incoming_dir}/${pkg_dir}"
}

log() {
  if [ "$debci_quiet" = 'false' ]; then
    echo "$@"
  fi
}

log_error() {
  echo "$@"
}

maybe_with_proxy() {
  if command -v auto-apt-proxy >/dev/null; then
    export http_proxy=$(auto-apt-proxy 2>/dev/null || true)
  fi
  "$@"
}

invoke_backend() {
  cmd="${1}"
  shift
  # shellcheck disable=SC2154
  "${debci_base_dir}/backends/${debci_backend}/${cmd}" "$@"
}

build_image_as_root() {
  sudo --preserve-env=MIRROR,AUTOPKGTEST_APT_SOURCES_FILE,HTTP_PROXY,http_proxy "$@"
}

job_is_completed() {
  if [ -z "${debci_api_server}" ]; then
    # cannot check, assume it's pending
    return 1
  fi

  local job_id
  job_id="$1"

  local state
  state="$(curl --retry 5 --silent "${debci_api_server}/api/v1/job_state/${job_id}" | jq --raw-output .state)"

  [ "${state}" = "completed" ]
}
