#!/bin/bash
# Action -Run
set -eu

ABOT_DEPLOY_DIR=/etc/rebaca-test-suite
ELASTIC_FILE_NAME=${ABOT_DEPLOY_DIR}/es-conf

tags_defined=1
no_report_needed=0


new_tags=

if [ $# -gt 0 ]; then
    TAG_NAMES="$1"
    #   echo "Tag(s) = ${TAG_NAMES}"
else
    #   echo "No tags specified - exiting"
    exit 1
fi

if [ ! -z "${TAG_NAMES}" ]; then
    #  echo "Tag names: ${TAG_NAMES}"

    #Split the tags and add the @ symbols
    IFS=', ' read -r -a array <<< "${TAG_NAMES}"
    for index in "${!array[@]}"
    do
        if [ ${index} -eq 0 ]; then
            new_tags="@${array[0]}"
        else
            #Add current tag only if not duplicate
            current_tag="${array[index]}"
            if [ `echo ${new_tags} | grep -c ${current_tag}` -eq 0 ]; then
                new_tags="${new_tags},@${current_tag}"
            fi
        fi
    done

    #Assign the tags variable accordingly.
    tags=$new_tags
fi

if [ -z "$tags" ]; then
    echo "No tags found for execution"
else
    echo "Running the test with the tags $tags"

    # status-set active  "Executing run action"
    ${ABOT_DEPLOY_DIR}/bin/tags_update_local $tags

    # Removing previous run artifacts
    rm -rf ${ABOT_DEPLOY_DIR}/log/*.*

    (cd ${ABOT_DEPLOY_DIR}; \
     # Perform mvn clean first
     mvn clean; \
     # Run the install target now
     mvn install -Dtest=RunScenarios -DrootDir=com/rebaca/abot || true)

    # Copying log artifacts to appropriate artifacts folder
    LAST_REPORT_DIR="$(ls -td -- ${ABOT_DEPLOY_DIR}/artifacts/*/ | head -n 1)"

    cp -R ${ABOT_DEPLOY_DIR}/log/*.* ${LAST_REPORT_DIR}

    # Process Test results and post to ElasticSearch
    touch ${ELASTIC_FILE_NAME}
    ES_CONF=`cat ${ELASTIC_FILE_NAME}`
    if [  -z "${ES_CONF}" ]; then
        echo "No ES conf defined - hence result not pushed to ES"
    else
        echo "Pushing Test result to ES"
        LAST_REPORT_FILE_NAME=`basename ${LAST_REPORT_DIR}`
        echo "Renaming Test result to ${LAST_REPORT_FILE_NAME}.json"
        cp ${ABOT_DEPLOY_DIR}/artifacts/TestResults.json ${ABOT_DEPLOY_DIR}/artifacts/${LAST_REPORT_FILE_NAME}.json
        python ${ABOT_DEPLOY_DIR}/bin/es-feed.py --elastic ${ES_CONF} --mappings  ${ABOT_DEPLOY_DIR}/bin/mappings.json \
               --filepath ${ABOT_DEPLOY_DIR}/artifacts/${LAST_REPORT_FILE_NAME}.json
    fi
fi
