#!/bin/sh

short_options='o'
long_options='print-output'

usage() {
  cat <<EOF
usage: debci test [OPTIONS] srcpkg

Options:
  -o, --print-output        print output directory after test finished

$@
EOF
}

set -eu

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

process_package() {
  # output directory for test-package/autopkgtest
  run_id=$(date +%Y%m%d_%H%M%S)
  local base_dir="$(autopkgtest_incoming_dir_for_package "$pkg")"
  adt_out_dir="${base_dir}/${run_id}"

  inc=0
  orig_run_id="$run_id"
  while [ -d "$adt_out_dir" ]; do
    # this in *very* unlikely to happen in production, but we need this for the
    # test suite
    run_id="${orig_run_id}.${inc}"
    adt_out_dir="${base_dir}/${run_id}"
  done

  mkdir -p "$(dirname $adt_out_dir)"
  start_timestamp=$(date +%s)


  if [ "$debci_quiet" = 'true' ]; then
    run_with_shared_lock "$debci_testbed_lock" test-package "$pkg" "$adt_out_dir" >/dev/null 2>&1 || true
  else
    run_with_shared_lock "$debci_testbed_lock" test-package "$pkg" "$adt_out_dir"  || true
  fi

  finish_timestamp=$(date +%s)

  find "$adt_out_dir" '(' \
    -name log -or \
    -name '*-stdout' -or \
    -name '*-stderr' ')' -exec gzip '{}' ';'

  echo $(($finish_timestamp - $start_timestamp)) >> "$adt_out_dir/duration"

  if [ -n "$print_output" ]; then
      echo "$adt_out_dir"
  fi
}

# defaults
index=''
print_output=''

while true; do
  case "$1" in
    -o|--print-output)
      print_output=true
      shift
      ;;
    --)
      shift
      break
      ;;
    *)
      shift
      ;;
  esac
done

if [ $# -eq 1 ]; then
  pkg="$1"
  process_package
else
  usage
  exit 1
fi
