#!/bin/bash

set -e


# The script used to execute the tool will be named with the
# ._wb prefix to avoid collision with any other files

LOG_FP=._wb/log.txt

# Make sure that the expected file exists
file_exists(){
    echo "$(date) Checking for file $1" >> $LOG_FP && \
    ( [ -e "${1}" ] || echo "File does not exist: $1" ) && \
    [ -e "${1}" ]
}

# Set the status of the dataset, while logging this action
set_status(){
    echo "$(date) Setting status of dataset to $1" >> $LOG_FP
    /bin/bash ._wb/helpers/set_dataset_attribute status $1
}

# Print the parameters being used for the tool
echo "Tool Parameters:"
cat ._wb/tool/params.json
echo

# Set all of the environment variables defined by the
# parameters for the launcher
file_exists ._wb/tool/run.sh
file_exists ._wb/tool/env
source ._wb/tool/env

# Set the status as RUNNING
set_status RUNNING

# Run the tool with the `run.sh` script defined by the
# tool developer. While running this command, route any
# messages to standard out or standard error to canonical
# filepaths
( /bin/bash ._wb/tool/run.sh \
2>> >(tee -a ._wb/error.txt ._wb/log.txt >(cat 1>&2) > /dev/null) \
1>> >(tee -a ._wb/output.txt ._wb/log.txt > /dev/null) && \
set_status COMPLETED ) || \
set_status FAILED
