#!/bin/bash

# When this script will be run, the packages your-application.rpm and your-application-redtest.rpm
# would have been installed on the target

PACKAGE_NAME="gps-binding"

# Install or reinstall dependencies
for p in afb-binding-devel afb-libpython afb-test-py afb-cmake-modules libdb-devel gpsd gpsd-clients gpsd-devel gpsd-libs userspace-rcu-devel; do
    sudo rpm -q $p && sudo dnf update -y $p || sudo dnf install -y $p 
done

# Install missing tools if needed
for p in g++ lcov; do
    command -v $p 2>/dev/null 2>&1 || sudo dnf install -y $p
done

# Create the directory where the logs need to be
LOG_DIR="/var/log/redtest/${PACKAGE_NAME}"
mkdir -p ${LOG_DIR}

# Run your tests
# To be filled by you! Remember, the log file needs to be in ".tap" format

function stop_gpsd {
        sudo systemctl stop gpsd.service >/dev/null
        sudo systemctl stop gpsd.socket >/dev/null
        pkill -9 gpsfake >/dev/null
        pkill -9 gpsd >/dev/null
}

echo "-- Stopping remaining gpsd & gpsfake instances --"
stop_gpsd

echo "--- Start test python gps binding ---"
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
gpsfake -S ${SCRIPT_DIR}/lorient.nmea &
export GCOV_PREFIX=${SCRIPT_DIR}/coverage_data/
export GCOV_PREFIX_STRIP=5
LD_LIBRARY_PATH=${SCRIPT_DIR}/coverage_data/${PACKAGE_NAME}/lib python3 ${SCRIPT_DIR}/tests.py --tap | tee /var/log/redtest/${PACKAGE_NAME}/tests.tap 2>&1

echo "--- Killing created gpsd & gpsfake instances ---"
stop_gpsd

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

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

# Clean previous coverage data
rm -f lcov_cobertura*
rm -rf lcov_cobertura-*

# Download lcov_cobertura tool
wget https://github.com/eriwen/lcov-to-cobertura-xml/releases/download/v2.1.1/lcov_cobertura-2.1.1.tar.gz
tar xzvf lcov_cobertura-2.1.1.tar.gz

# Generate lcov info file
rm -f app.info app_filtered.info
lcov --directory ${SCRIPT_DIR}/coverage_data/ --capture --output-file app.info

# Remove system headers and other noise
lcov --remove app.info '/usr/*' -o app_filtered.info

# Show coverage summary (will appear in GitLab CI logs)
lcov --list app_filtered.info

# Generate Cobertura-compatible XML for GitLab coverage
PYTHONPATH=./lcov_cobertura-2.1.1/ python3 -m lcov_cobertura app_filtered.info -o ${LOG_DIR}/coverage.xml


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

##########################
# report status
##########################
test -f /var/log/redtest/${PACKAGE_NAME}/tests.tap && grep -viq '^not ok' /var/log/redtest/${PACKAGE_NAME}/tests.tap
