#!/bin/bash -e
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TFLM_ROOT_DIR=${SCRIPT_DIR}/..

# The renode script for the board being emulated.
RESC_PATH=${TFLM_ROOT_DIR}/testing/bluepill.resc

# Renode's entrypoint for using the Robot Framework.
RENODE_TEST_SCRIPT=${TFLM_ROOT_DIR}/tools/make/downloads/renode/test.sh

if [ ! -f "${RENODE_TEST_SCRIPT}" ]; then
  echo "The renode test script: ${RENODE_TEST_SCRIPT} does not exist. Please " \
       "make sure that you have correctly installed Renode for TFLM. See " \
       "tensorflow/lite/micro/docs/renode.md for more details."
  exit 1
fi

if ! ${RENODE_TEST_SCRIPT} &> /dev/null
then
  echo "The following command failed: ${RENODE_TEST_SCRIPT}. Please " \
       "make sure that you have correctly installed Renode for TFLM. See " \
       "tensorflow/lite/micro/docs/renode.md for more details."
  exit 1
fi

exit_code=0

# The logs from this script will go in the RESULTS_DIRECTORY. These include:
#  1. RENODE_LOG: Output log from the renode process.
#  2. html and xml files generated by the Robot Framework.
#
# Note that with the current approach (in bluepill.robot), multiple test
# binaries are run in a loop and RENODE_LOG only has logs from the last test
# binary since it is deleted prior to running each test binary.
RESULTS_DIRECTORY=/tmp/renode_bluepill_logs
mkdir -p ${RESULTS_DIRECTORY}
RENODE_LOG=${RESULTS_DIRECTORY}/renode_log.txt

ROBOT_COMMAND="${RENODE_TEST_SCRIPT} ${TFLM_ROOT_DIR}/testing/bluepill.robot \
  -r ${RESULTS_DIRECTORY} \
  --variable RESC:${RESC_PATH} \
  --variable RENODE_LOG:${RENODE_LOG} \
  --variable DIR_WITH_TESTS:${1}"

echo "${ROBOT_COMMAND}"

if ! ${ROBOT_COMMAND}
then
  exit_code=1
fi

if [ $exit_code -eq 0 ]
then
  echo "PASS"
else
  echo "UART LOGS:"
  # Extract output from renode log
  cat ${RENODE_LOG} |grep 'uartSemihosting' |sed 's/^.*from start] *//g'
fi

exit $exit_code
