#!/usr/bin/env bash
# run the build in a docker container
# requirements: env var GITLAB_BUILD_REPOSITORY_TOKEN must be defined for selenium tests to work
set -ex

# find the dir two levels up from here, home of all the repositories
COMPUTED_ROOT=$(readlink -e $(dirname "$0")/../../)
# NTECH_ROOT should be the same, but if available use it so user can do their own thing.
NTECH_ROOT=${NTECH_ROOT:-$COMPUTED_ROOT}

# start openldap test server container
if ! docker images | grep openldap; then
  docker build -t openldap -f "${NTECH_ROOT}"/mission-portal/docker/openldap/Dockerfile "${NTECH_ROOT}"/mission-portal/docker/openldap
fi
if ! docker ps | grep openldap; then
  if docker ps -a --filter "name=openldap" | grep openldap; then
    docker start openldap
  else
    docker run -d -p 5900-5901:5900-5901 -p 389:389 -p 636:636 --name openldap openldap
  fi
fi

name=cfengine-selenium-tests

# NTECH_ROOT should have a usable deb package in artifacts directory
if docker ps -a | grep $name; then
  docker start $name
else
  time docker run -d --privileged -e GITLAB_BUILD_REPOSITORY_TOKEN -p 8443:443 -v "${NTECH_ROOT}":/data --name $name cfengine/cfengine-selenium-tests:php82-ubuntu22
fi


# setup networking
if ! docker network ls | grep $name; then
  docker network create $name
  docker network connect $name openldap
  docker network connect $name $name
fi

# TODO here we could just have "started things up" and let the user decide whether they want to run all tests or one
#exit 0
# TODO also, move the composer install/update found later here into the setup

set +e
time docker exec -i $name bash -c 'cd /data; ./mission-portal/ci/run.sh'
rc=$? # capture exit code of tests run
# copy coverage report regardless, and if none, that's OK
# if we ensure build/coverage exists then the following command doesn't fail at all even if it doesnt, otherwise a message comes out with "Error: NO such container:path which could be misleading
docker exec -t $name bash -c "sudo mkdir -p /data/mission-portal/build/coverage"
sudo mkdir -p "${NTECH_ROOT}/artifacts/coverage"
sudo chown -R $USER "${NTECH_ROOT}/artifacts/coverage"
docker cp $name:/data/mission-portal/build/coverage "${NTECH_ROOT}/artifacts/" || true

if [ $rc -ne 0 ]; then
  # in case docker changes permissions so we can't fiddle with things
  sudo chown -R $USER "${NTECH_ROOT}/artifacts"
#  docker cp $name:/data/artifacts "${NTECH_ROOT}/"
  exit $rc
fi
