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

ABOT_DEPLOY_DIR=/etc/rebaca-test-suite
ELASTIC_FILE_NAME=${ABOT_DEPLOY_DIR}/es-conf
ABOT_TAGS_DIR=${ABOT_DEPLOY_DIR}/tags
tags_defined=1

TAG_NAMES=$(action-get tagnames)
TAG_FILE_NAME=$(action-get filename)

if [ ! -z "$TAG_FILE_NAME" ]; then
    juju-log "Tag file specified: $TAG_FILE_NAME"
else
    #Assign default file name
    TAG_FILE_NAME=tags
fi

new_tags=

if [ -z "${TAG_NAMES}" ]; then
    juju-log "No tag names specified"
    tags_defined=0
    #Check if filename specified and file exists
    if [ ! -z "${TAG_FILE_NAME}" ] && [ -f ${ABOT_TAGS_DIR}/${TAG_FILE_NAME} ] ; then
        tags=`cat ${ABOT_TAGS_DIR}/${TAG_FILE_NAME}`
    fi
else
    juju-log "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
    juju-log "No tags found for execution"
else
    juju-log "Running the test with the tags ${tags}"

    ${ABOT_DEPLOY_DIR}/bin/tags_update ${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
