#!/usr/bin/env bash

set -eu

declare work_dir=$(pwd)

if [ 'run' = "$1" ]; then
	declare no_exit="--no-exit";
fi

cd $PROJECT_DIR

echo "Running 'codecept $@' in Docker..."
~/.composer/vendor/bin/codecept $@ --env docker --no-redirect $no_exit

if [ 'run' = "$1" ]; then
	declare test_output="tests/_output";
	if [ -n "$(ls $test_output )" ]; then
		echo 'Setting result files permissions'.
		chmod 777 -R ${test_output}/*
	fi

	# Clean coverage.xml and clean up PCOV configurations.
	if [ -f "${test_output}/coverage.xml" ]; then
		echo 'Cleaning coverage.xml for deployment...'
		pattern="$PROJECT_DIR/"
		sed -i "s~$pattern~~g" "$test_output"/coverage.xml
	fi

	# Check results and exit accordingly.
	if [ -f "$test_output/failed" ]; then
		echo "Uh oh, some went wrong." >> /dev/stderr
		exit 1
	else
		echo "Woohoo! It's working!"
		exit 0
	fi
fi

cd $work_dir
