#!/usr/bin/env bash
set -ex

if [ "$#" -ne 2 ]; then
    echo "Usage: $0 <selenium-log-path> <junit-xml-report-path>"
    exit 1
fi

selenium_log="$1"
junit_report_path="$2"

# Search for the JavaScript errors in the selenium.log and mark result as fail if found and generate junit report
js_errors_count=$(grep -c "JavaScript error: https://127.0.0.1" "$selenium_log" || echo 0)
if [ "$js_errors_count" -gt "0" ]; then
    echo "$js_errors_count JS error logs found"
    # Generate JUnit XML report
    {
        echo '<?xml version="1.0" encoding="UTF-8"?>'
        echo "<testsuite name=\"SeleniumLogFileTestSuite\" tests=\"$js_errors_count\" failures=\"$js_errors_count\" errors=\"0\">"
        grep "JavaScript error: https://127.0.0.1" "$selenium_log" | while IFS= read -r error_line
          do
          echo '<testcase classname="SeleniumLogFileTests" name="CheckForJavaScriptErrors">'
          echo '<failure type="JavaScriptError">'
          echo "$error_line" 
          echo '</failure>'
          echo '</testcase>'
          done
        echo '</testsuite>'
    } > "$junit_report_path"
fi
