#!/usr/bin/env bash
set -e

SCRIPTNAME=$(basename $0)

if [[ $# -lt 3 ]]; then
    cat << EOF
Usage: ${SCRIPTNAME} <scenario> <version> <version> [--configs config1,config2,...] [--artifacts path]

Versions can be specified in the following formats:
    - "ddtrace==0.51.0" - to install a specific version from PyPI
    - "Datadog/dd-trace-py@v0.51.0 - to install a specific version from GitHub
    - "." - to install the current local version

Examples:
    ${SCRIPTNAME} span ddtrace==0.51.0 ddtrace==0.50.0
    ${SCRIPTNAME} span Datadog/dd-trace-py@v0.51.0 Datadog/dd-trace-py@v0.50.0
    ${SCRIPTNAME} span ddtrace==2.8.4 .
    ${SCRIPTNAME} span ddtrace==0.51.0 ddtrace==0.50.0 --artifacts ./artifacts/
    ${SCRIPTNAME} django_simple ddtrace==2.8.4 . --configs tracer,baseline

EOF
    exit 1
fi

function expand_git_version {
    gitpattern="dd-trace-py@"
    version=${1}

    if [[ $version =~ $gitpattern ]]; then
        version="git+https://github.com/${version}"
    fi

    # If the user provides "." they want the local version, which gets mapped to `/src/` in the container
    if [[ $version == "." ]]; then
        version="/src/"
    fi
    echo $version
}

SCENARIO="$1"
shift
DDTRACE_V1="$1"
shift
DDTRACE_V2="$1"
shift

ARTIFACTS=""
CONFIGS=""

# Parse remaining arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --configs)
            CONFIGS="$2"
            shift # past argument
            shift # past value
            ;;
        --artifacts)
            ARTIFACTS="$2"
            shift # past argument
            shift # past value
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done


# Build scenario image
TAG="dd-trace-py/perf-${SCENARIO}"
scripts/perf-build-scenario "${SCENARIO}" "${TAG}"

CMD="docker run -it --rm --network host"
if [[ -n ${ARTIFACTS} ]]; then
   # Resolve artifacts to an absolute path
   ARTIFACTS="$(echo $ARTIFACTS | python -c 'import os,sys; print(os.path.abspath(sys.stdin.read()))')"
   mkdir -p ${ARTIFACTS}
   CMD+=" -v ${ARTIFACTS}:/artifacts/"
fi
CMD+=" -v $(pwd):/src/ \
  -e PROFILE_BENCHMARKS=${PROFILE_BENCHMARKS:-0} \
  -e DD_FAST_BUILD=1 \
  -e CMAKE_BUILD_PARALLEL_LEVEL=12 \
  -e CARGO_BUILD_JOBS=12 \
  -e DDTRACE_INSTALL_V1=$(expand_git_version $DDTRACE_V1) \
  -e DDTRACE_INSTALL_V2=$(expand_git_version $DDTRACE_V2) \
  -e BENCHMARK_CONFIGS=${CONFIGS} \
  ${TAG}"

$CMD
