#!/bin/bash
# replace da shit alter, kann ja nicht sooo schwer sein :/
# um dann später bei failure oder pass den kram zu machen...""

is_test_case=false

report="test-report.xml"
# used to save blakeks
potential_failure="failure.tmp"

xml_header="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"

open_suite_xml="<testsuite>"
close_suite_XML="</testsuite>"

# Attention closing bracket is missing!
open_test_case="<testcase classname=\"osmo\" name=\""
close_test_case="</testcase>"

open_failure_tag="<failure name=\"failure\"><![CDATA["
close_failure_tag="]]></failure>"

failure_tag() {
  # sanitize by removing empty blank (0x1b) 27
  sed -i 's// /g' $potential_failure
  # $1 to visualize whether it is a TIMEOUT or FAILURE
  echo "$open_failure_tag $1" >> $report
  cat $potential_failure >> $report
  echo $close_failure_tag >> $report
  echo $close_test_case >> $report

  is_test_case=false
}

echo $xml_header > $report
echo $open_suite_xml >> $report

while read line; do
  # echoes line already
  if grep -E '^Test' <<< $line ; then

    test_case=$(echo $line | cut -d ' ' -f2)

    echo "${open_test_case}${test_case}\">" >> $report
    echo $line > $potential_failure

    is_test_case=true

  # if only first conditions sometimes appear two PASSED inside one testcase?
  elif [ "$(grep "PASSED" <<< $line)" != "" ] && [ $is_test_case = true ]; then
    echo $close_test_case >> $report
    is_test_case=false

  elif grep "FAILED" <<< $line; then
    failure_tag "!!! FAILED !!!"

  elif grep "TIMEOUT" <<< $line; then
    failure_tag "!!! TIMEOUT !!!"

  elif $is_test_case = true ; then
    echo $line >> $potential_failure
  fi

done < TESTYAAWW/verbose_failure.log

# closing XML report
echo $close_suite_XML >> $report

sed -i 's// /g' $potential_failure
