#!/bin/bash

# Exit on error
set -e

DIR="$(cd "$(dirname "$0")" && pwd)"
ENV_FILE="$DIR/../.env"
SUMMARY_FILE="$DIR/../summary.html"

if [ -z "$1" ]
  then
    echo "No test file specified."
    exit 1
fi

if [ -z "$2" ]
  then
    echo "No scenario specified."
    exit 1
fi

# Get the test file to run from the first argument
TEST_FILE="$DIR/../tests/$1/index.js"

# Read environment variables from file if the file exists
if [ -f "$ENV_FILE" ]; then
  echo "Reading environment variables from file"
  export $(grep -v '^#' $ENV_FILE | xargs)
fi;

# Exit hook
trap onExit EXIT
onExit() {
  echo "Exiting"

  echo "Stopping DataDog agent container"
  docker stop datadog

  # Killing child processes seems to cancel the Github Actions worfklow,
  # so we're skipping this step if running inside a Github Action
  if [ -z "$CI" ]; then
    echo "Killing child processess"
    kill 0
  fi;
}

# Run the DataDog agent in a docker container
echo "Launching DataDog agent"
DOCKER_CONTENT_TRUST=1 \
docker run --rm -d \
    --name datadog \
    -v /var/run/docker.sock:/var/run/docker.sock:ro \
    -v /proc/:/host/proc/:ro \
    -v /sys/fs/cgroup/:/host/sys/fs/cgroup:ro \
    -e DD_SITE="datadoghq.com" \
    -e DD_API_KEY=$DD_API_KEY \
    -e DD_DOGSTATSD_NON_LOCAL_TRAFFIC=1 \
    -p 8125:8125/udp \
    datadog/agent:latest

# Run the test sending the output to DataDog
echo "Launching tests"
SCENARIO_NAME=$2 SUMMARY_FILE=$SUMMARY_FILE K6_STATSD_ENABLE_TAGS=true k6 run --out statsd $TEST_FILE
