#!/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 "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 "Setting status of dataset to $1" >> $LOG_FP
    /bin/bash ._wb/helpers/set_dataset_attribute status $1
}

# 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

# 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 >(cat 1>&2)) \
1>> >(tee -a ._wb/output.txt ) && \
set_status COMPLETED ) || \
set_status FAILED
