#!/bin/bash

ls -l /bbx/input
ls -l /bbx/output
ls -l /bbx/tmp
ls -l /bbx/metadata
ls -l /bbx/reference

# exit script if one command fails
set -o errexit

# exit script if Variable is not set
set -o nounset

INPUT=/bbx/input/biobox.yaml # this file is generate by the benchmarking platform to tell where input files are located.
OUTPUT=/bbx/output
TMP_DIR=/bbx/tmp
METADATA=/bbx/metadata/

# Since this script is the entrypoint to your container
# you can access the task in `docker run task` as the first argument
TASK=$1

# Ensure the biobox.yaml file is valid, ensure a match between the biobox and the benchmarking platform inputs
validate-biobox-file \
  --input ${INPUT} \
  --schema /schema.yaml \

# Parse the read locations from this file
READS=$(yaml2json < ${INPUT} \
        | jq --raw-output '.arguments[] | select(has("fastq")) | .fastq[].value | "-short \(.)"' \
        | tr '\n' ' ')

# Use grep to get $TASK in /Taskfile
CMD=$(egrep ^${TASK}: /Taskfile | cut -f 2 -d ':')
if [[ -z ${CMD} ]]; then
  echo "Abort, no task found for '${TASK}'."
  exit 1
fi

# if /bbx/metadata is mounted create log.txt
if [ -d "$METADATA" ]; then
  CMD="($CMD) >& $METADATA/log.txt"
fi

# Run the given task with eval.
# Eval evaluates a String as if you would use it on a command line.
eval ${CMD}

cat << EOF > ${OUTPUT}/biobox.yaml
---
version: 0.9.0
arguments:
    profiling:
       - value: ${OUTPUT}/profile.tsv
         type: bioboxes.org:/profling:0.9
    binning:
       - value: ${OUTPUT}/bins.tsv
         type: bioboxes.org:/binning:0.9.1
EOF
