
#!/usr/bin/env bash
set -euo pipefail

### USAGE
### RUN FROM THE ROOT OF THEBUILD TREE

# Run an echo to tell us on which branch and commit we are running
echo "Running MTR S3 tests on branch '$(git rev-parse --abbrev-ref HEAD)' commit '$(git rev-parse HEAD)'"

# -----------------------------
# S3 config (override via env)
# -----------------------------
: "${S3_HOST_NAME:=minio.mariadb.org}"
: "${S3_PORT:=443}"
: "${S3_ACCESS_KEY:=}"
: "${S3_SECRET_KEY:=}"
: "${S3_BUCKET:=}"
: "${S3_USE_HTTP:=OFF}"            # OFF/ON
: "${S3_PROTOCOL_VERSION:=Path}"
: "${S3_REGION:=garage}"

# -----------------------------
# MTR config
# -----------------------------
: "${MTR_DIR:=mysql-test}"
: "${JOBS:=14}"
: "${PARALLEL:=$((JOBS * 2))}"
: "${CONCURRENCY:=2}"

# Port planning
: "${PORT_MIN:=5001}"
: "${PORT_MAX:=32767}"
: "${PORTS_RESERVED:=10}"          # docs: port_base..port_base+9 reserved

# IMPORTANT: MTR_PORT_BASE must be divisible by 10 (MTR rounds down otherwise)
: "${PORT_BASE_START:=20000}"      # divisible by 10
: "${PORT_BASE_STEP:=100}"         # divisible by 10; spacing between concurrent MTR instances

: "${VARDIR_BASE:=/tmp/mtr-s3}"

# ---- validate required env ----
if [[ -z "${S3_ACCESS_KEY}" || -z "${S3_SECRET_KEY}" || -z "${S3_BUCKET}" ]]; then
  echo "ERROR: Missing required env vars: S3_ACCESS_KEY, S3_SECRET_KEY, S3_BUCKET" >&2
  exit 2
fi


export S3_REGION
export S3REGION="$S3_REGION"

# Export for mysql-test-run.pl / tests
export S3_HOST_NAME S3_PORT S3_ACCESS_KEY S3_SECRET_KEY S3_BUCKET S3_USE_HTTP S3_PROTOCOL_VERSION

cd "$MTR_DIR"

round_down_to_10() {
  local n="$1"
  echo $(( (n / 10) * 10 ))
}

check_port_base() {
  local base="$1"
  local base10
  base10="$(round_down_to_10 "$base")"
  local high=$((base10 + PORTS_RESERVED - 1))

  if (( base10 < PORT_MIN || high > PORT_MAX )); then
    echo "ERROR: MTR_PORT_BASE window out of range: ${base10}-${high} (allowed ${PORT_MIN}-${PORT_MAX})" >&2
    echo "Hint: lower PORT_BASE_START / PORT_BASE_STEP / CONCURRENCY." >&2
    exit 3
  fi

  # warn if caller provided a non-multiple-of-10
  if (( base != base10 )); then
    echo "WARN: PORT_BASE ${base} not divisible by 10; MTR will round down to ${base10}" >&2
  fi

  echo "$base10"
}

run_one() {
  local name="$1"
  local base_in="$2"
  local vardir="${VARDIR_BASE}-${name}"

  mkdir -p "$vardir"

  # Per docs: setting MTR_PORT_BASE (and not "auto") overrides build-thread
  local base
  base="$(check_port_base "$base_in")"
  export MTR_PORT_BASE="$base"

  echo "==> MTR ${name}: MTR_PORT_BASE=${MTR_PORT_BASE} vardir=${vardir} bucket=${S3_BUCKET}"

  perl mysql-test-run.pl \
    --force \
    --parallel="${PARALLEL}" \
    --suite=s3 \
    --vardir="${vardir}"
}

pids=()

for i in $(seq 1 "$CONCURRENCY"); do
  name="$(printf '%02d' "$i")"
  base=$((PORT_BASE_START + (i - 1) * PORT_BASE_STEP))

  run_one "$name" "$base" & pids+=("$!")
done

rc=0
for pid in "${pids[@]}"; do
  if ! wait "$pid"; then
    rc=1
  fi
done

exit "$rc"
