#!/bin/bash
set -euo pipefail
set -x

PACKAGE_NAME="helloworld-binding"

echo "--- Start test python hello world binding ---"

SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
PROJECT_ROOT=$(cd -- "${SCRIPT_DIR}/.." &>/dev/null && pwd)

COVERAGE_DIR="${SCRIPT_DIR}/coverage_data"
BUILD_DIR="${PROJECT_ROOT}/build"
INSTALLED_LIB_DIR="/usr/redpesk/${PACKAGE_NAME}/lib"

# Detect source tree location.
if [[ -f "${SCRIPT_DIR}/sources/src/helloworld.c" ]]; then
    SOURCE_BASE="${SCRIPT_DIR}/sources"
else
    SOURCE_BASE="${PROJECT_ROOT}"
fi

# Prepare coverage output directory.
mkdir -p "${COVERAGE_DIR}"

# Clean previous runtime coverage data only.
find "${COVERAGE_DIR}" -name '*.gcda' -delete 2>/dev/null || true

export GCOV_PREFIX="${COVERAGE_DIR}/"
export GCOV_PREFIX_STRIP=5

# Build LD_LIBRARY_PATH dynamically.
LIB_PATHS=()
if [[ -d "${INSTALLED_LIB_DIR}" ]]; then
    LIB_PATHS+=("${INSTALLED_LIB_DIR}")
fi
if [[ -d "${BUILD_DIR}" ]]; then
    LIB_PATHS+=("${BUILD_DIR}")
fi

if [[ ${#LIB_PATHS[@]} -eq 0 ]]; then
    echo "ERROR: no library path found for ${PACKAGE_NAME}" >&2
    exit 1
fi

LD_LIBRARY_PATH_VALUE="$(IFS=:; echo "${LIB_PATHS[*]}")"
if [[ -n "${LD_LIBRARY_PATH:-}" ]]; then
    LD_LIBRARY_PATH_VALUE="${LD_LIBRARY_PATH_VALUE}:${LD_LIBRARY_PATH}"
fi
export LD_LIBRARY_PATH="${LD_LIBRARY_PATH_VALUE}"

# Create the directory where logs need to be written.
LOG_DIR="${LOG_DIR:-/var/log/redtest/${PACKAGE_NAME}}"
if ! mkdir -p "${LOG_DIR}" 2>/dev/null || [[ ! -w "${LOG_DIR}" ]]; then
    LOG_DIR="${PROJECT_ROOT}/logs"
    mkdir -p "${LOG_DIR}"
fi
export LOG_DIR

python3 "${SCRIPT_DIR}/tests.py" --tap | tee "${LOG_DIR}/helloworld.tap" 2>&1

##########################
# Coverage report section
##########################

echo "--- Generating coverage reports ---"

rm -f app.info

if python3 -m lcov_cobertura --help >/dev/null 2>&1; then
    echo "lcov_cobertura installed successfully."
else
    python3 -m pip install lcov_cobertura
fi

LCOV_ARGS=(
    --directory "${COVERAGE_DIR}"
    --base-directory "${SOURCE_BASE}"
    --capture
    --no-external
    --output-file app.info
)

# In local mode, .gcno files are in ./build, not in coverage_data.
if ! find "${COVERAGE_DIR}" -name '*.gcno' -print -quit | grep -q .; then
    LCOV_ARGS+=(--build-directory "${PROJECT_ROOT}")
fi

lcov "${LCOV_ARGS[@]}"

lcov --summary app.info
lcov_cobertura app.info -o "${LOG_DIR}/coverage.xml"

echo "--- Coverage report generated at ${LOG_DIR}/ ---"

##########################
# Report status
##########################
test -f "${LOG_DIR}/helloworld.tap" && grep -viq '^not ok' "${LOG_DIR}/helloworld.tap"
