#!/usr/bin/env bash

# sgdemux add_bases2fastq
# 
# This wrapper script is auto-generated by viash 0.9.0 and is thus a derivative
# work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data
# Intuitive.
# 
# The component may contain files which fall under a different license. The
# authors of this component should specify the license in the header of such
# files, or include a separate license file detailing the licenses of all included
# files.
# 
# Component authors:
#  * Dries Schaumont (author, maintainer)

set -e

if [ -z "$VIASH_TEMP" ]; then
  VIASH_TEMP=${VIASH_TEMP:-$VIASH_TMPDIR}
  VIASH_TEMP=${VIASH_TEMP:-$VIASH_TEMPDIR}
  VIASH_TEMP=${VIASH_TEMP:-$VIASH_TMP}
  VIASH_TEMP=${VIASH_TEMP:-$TMPDIR}
  VIASH_TEMP=${VIASH_TEMP:-$TMP}
  VIASH_TEMP=${VIASH_TEMP:-$TEMPDIR}
  VIASH_TEMP=${VIASH_TEMP:-$TEMP}
  VIASH_TEMP=${VIASH_TEMP:-/tmp}
fi

# define helper functions
# ViashQuote: put quotes around non flag values
# $1     : unquoted string
# return : possibly quoted string
# examples:
#   ViashQuote --foo      # returns --foo
#   ViashQuote bar        # returns 'bar'
#   Viashquote --foo=bar  # returns --foo='bar'
function ViashQuote {
  if [[ "$1" =~ ^-+[a-zA-Z0-9_\-]+=.+$ ]]; then
    echo "$1" | sed "s#=\(.*\)#='\1'#"
  elif [[ "$1" =~ ^-+[a-zA-Z0-9_\-]+$ ]]; then
    echo "$1"
  else
    echo "'$1'"
  fi
}
# ViashRemoveFlags: Remove leading flag
# $1     : string with a possible leading flag
# return : string without possible leading flag
# examples:
#   ViashRemoveFlags --foo=bar  # returns bar
function ViashRemoveFlags {
  echo "$1" | sed 's/^--*[a-zA-Z0-9_\-]*=//'
}
# ViashSourceDir: return the path of a bash file, following symlinks
# usage   : ViashSourceDir ${BASH_SOURCE[0]}
# $1      : Should always be set to ${BASH_SOURCE[0]}
# returns : The absolute path of the bash file
function ViashSourceDir {
  local source="$1"
  while [ -h "$source" ]; do
    local dir="$( cd -P "$( dirname "$source" )" >/dev/null 2>&1 && pwd )"
    source="$(readlink "$source")"
    [[ $source != /* ]] && source="$dir/$source"
  done
  cd -P "$( dirname "$source" )" >/dev/null 2>&1 && pwd
}
# ViashFindTargetDir: return the path of the '.build.yaml' file, following symlinks
# usage   : ViashFindTargetDir 'ScriptPath'
# $1      : The location from where to start the upward search
# returns : The absolute path of the '.build.yaml' file
function ViashFindTargetDir {
  local source="$1"
  while [[ "$source" != "" && ! -e "$source/.build.yaml" ]]; do
    source=${source%/*}
  done
  echo $source
}
# see https://en.wikipedia.org/wiki/Syslog#Severity_level
VIASH_LOGCODE_EMERGENCY=0
VIASH_LOGCODE_ALERT=1
VIASH_LOGCODE_CRITICAL=2
VIASH_LOGCODE_ERROR=3
VIASH_LOGCODE_WARNING=4
VIASH_LOGCODE_NOTICE=5
VIASH_LOGCODE_INFO=6
VIASH_LOGCODE_DEBUG=7
VIASH_VERBOSITY=$VIASH_LOGCODE_NOTICE

# ViashLog: Log events depending on the verbosity level
# usage: ViashLog 1 alert Oh no something went wrong!
# $1: required verbosity level
# $2: display tag
# $3+: messages to display
# stdout: Your input, prepended by '[$2] '.
function ViashLog {
  local required_level="$1"
  local display_tag="$2"
  shift 2
  if [ $VIASH_VERBOSITY -ge $required_level ]; then
    >&2 echo "[$display_tag]" "$@"
  fi
}

# ViashEmergency: log events when the system is unstable
# usage: ViashEmergency Oh no something went wrong.
# stdout: Your input, prepended by '[emergency] '.
function ViashEmergency {
  ViashLog $VIASH_LOGCODE_EMERGENCY emergency "$@"
}

# ViashAlert: log events when actions must be taken immediately (e.g. corrupted system database)
# usage: ViashAlert Oh no something went wrong.
# stdout: Your input, prepended by '[alert] '.
function ViashAlert {
  ViashLog $VIASH_LOGCODE_ALERT alert "$@"
}

# ViashCritical: log events when a critical condition occurs
# usage: ViashCritical Oh no something went wrong.
# stdout: Your input, prepended by '[critical] '.
function ViashCritical {
  ViashLog $VIASH_LOGCODE_CRITICAL critical "$@"
}

# ViashError: log events when an error condition occurs
# usage: ViashError Oh no something went wrong.
# stdout: Your input, prepended by '[error] '.
function ViashError {
  ViashLog $VIASH_LOGCODE_ERROR error "$@"
}

# ViashWarning: log potentially abnormal events
# usage: ViashWarning Something may have gone wrong.
# stdout: Your input, prepended by '[warning] '.
function ViashWarning {
  ViashLog $VIASH_LOGCODE_WARNING warning "$@"
}

# ViashNotice: log significant but normal events
# usage: ViashNotice This just happened.
# stdout: Your input, prepended by '[notice] '.
function ViashNotice {
  ViashLog $VIASH_LOGCODE_NOTICE notice "$@"
}

# ViashInfo: log normal events
# usage: ViashInfo This just happened.
# stdout: Your input, prepended by '[info] '.
function ViashInfo {
  ViashLog $VIASH_LOGCODE_INFO info "$@"
}

# ViashDebug: log all events, for debugging purposes
# usage: ViashDebug This just happened.
# stdout: Your input, prepended by '[debug] '.
function ViashDebug {
  ViashLog $VIASH_LOGCODE_DEBUG debug "$@"
}

# find source folder of this component
VIASH_META_RESOURCES_DIR=`ViashSourceDir ${BASH_SOURCE[0]}`

# find the root of the built components & dependencies
VIASH_TARGET_DIR=`ViashFindTargetDir $VIASH_META_RESOURCES_DIR`

# define meta fields
VIASH_META_NAME="sgdemux"
VIASH_META_FUNCTIONALITY_NAME="sgdemux"
VIASH_META_EXECUTABLE="$VIASH_META_RESOURCES_DIR/$VIASH_META_NAME"
VIASH_META_CONFIG="$VIASH_META_RESOURCES_DIR/.config.vsh.yaml"
VIASH_META_TEMP_DIR="$VIASH_TEMP"


# ViashHelp: Display helpful explanation about this executable
function ViashHelp {
  echo "sgdemux add_bases2fastq"
  echo ""
  echo "Demultiplex sequence data generated on Singular Genomics' sequencing"
  echo "instruments."
  echo ""
  echo "Input:"
  echo "    -f, --fastqs"
  echo "        type: file, required parameter, multiple values allowed, file must exist"
  echo "        example: sample1_r1.fq;sample1_r2.fq;sample2_r1.fq;sample2_r2.fq"
  echo "        Path to the input FASTQs, or path prefix if not a file"
  echo ""
  echo "    -s, --sample_metadata"
  echo "        type: file, required parameter, file must exist"
  echo "        Path to the sample metadata CSV file including sample names and barcode"
  echo "        sequences"
  echo ""
  echo "Output:"
  echo "    --sample_fastq"
  echo "        type: file, required parameter, output, file must exist"
  echo "        example: output"
  echo "        The directory containing demultiplexed sample FASTQ files."
  echo ""
  echo "    --metrics"
  echo "        type: file, output, file must exist"
  echo "        example: metrics.tsv"
  echo "        Demultiplexing summary statisitcs:"
  echo "          - control_reads_omitted: The number of reads that were omitted for"
  echo "        being control reads."
  echo "          - failing_reads_omitted: The number of reads that were omitted for"
  echo "        having failed QC."
  echo "          - total_templates: The total number of template reads that were"
  echo "        output."
  echo ""
  echo "    --most_frequent_unmatched"
  echo "        type: file, output, file must exist"
  echo "        example: most_frequent_unmatched.tsv"
  echo "        It contains the (approximate) counts of the most prevelant observed"
  echo "        barcode sequences"
  echo "        that did not match to one of the expected barcodes. Can only be created"
  echo "        when 'most_unmatched_to_output'"
  echo "        is not set to 0."
  echo ""
  echo "    --sample_barcode_hop_metrics"
  echo "        type: file, output, file must exist"
  echo "        example: sample_barcode_hop_metrics.tsv"
  echo "        File containing the frequently observed barcodes that are unexpected"
  echo "        combinations of expected barcodes in a dual-indexed run."
  echo ""
  echo "    --per_project_metrics"
  echo "        type: file, output, file must exist"
  echo "        example: per_project_metrics.tsv"
  echo "        Aggregates the metrics by project (aggregates the metrics across samples"
  echo "        with the same project) and"
  echo "        has the same columns as \`--metrics\`. In this case, sample_ID will"
  echo "        contain the project name (or None if no project is given)."
  echo "        THe barcode will contain all Ns. The undetermined sample will not be"
  echo "        aggregated with any other sample."
  echo ""
  echo "    --per_sample_metrics"
  echo "        type: file, output, file must exist"
  echo "        example: per_sample_metrics.tsv"
  echo "        Tab-separated file containing statistics per sample."
  echo ""
  echo "Arguments:"
  echo "    -r, --read_structures"
  echo "        type: string, multiple values allowed"
  echo "        Read structures, one per input FASTQ. Do not provide when using a path"
  echo "        prefix for FASTQs"
  echo ""
  echo "    -m, --allowed_mismatches"
  echo "        type: integer"
  echo "        example: 1"
  echo "        Number of allowed mismatches between the observed barcode and the"
  echo "        expected barcode"
  echo ""
  echo "    -d, --min_delta"
  echo "        type: integer"
  echo "        example: 2"
  echo "        The minimum allowed difference between an observed barcode and the"
  echo "        second closest expected barcode"
  echo ""
  echo "    -F, --free_ns"
  echo "        type: integer"
  echo "        example: 1"
  echo "        Number of N's to allow in a barcode without counting against the"
  echo "        allowed_mismatches"
  echo ""
  echo "    -N, --max_no_calls"
  echo "        type: integer"
  echo "        Max no-calls (N's) in a barcode before it is considered unmatchable."
  echo "        A barcode with total N's greater than 'max_no_call' will be considered"
  echo "        unmatchable."
  echo ""
  echo "    -M, --quality_mask_threshold"
  echo "        type: integer, multiple values allowed"
  echo "        Mask template bases with quality scores less than specified value(s)."
  echo "        Sample barcode/index and UMI bases are never masked. If provided either"
  echo "        a single value,"
  echo "        or one value per FASTQ must be provided."
  echo ""
  echo "    -C, --filter_control_reads"
  echo "        type: boolean_true"
  echo "        Filter out control reads"
  echo ""
  echo "    -Q, --filter_failing_quality"
  echo "        type: boolean_true"
  echo "        Filter reads failing quality filter"
  echo ""
  echo "    -T, --output_types"
  echo "        type: string, multiple values allowed"
  echo "        example: T"
  echo "        choices: [ T, B, S, M ]"
  echo "        The types of output FASTQs to write."
  echo "        For each read structure, all segment types listed will be output to a"
  echo "        FASTQ file."
  echo "        These may be any of the following:"
  echo "         - \`T\` - Template bases"
  echo "         - \`B\` - Sample barcode bases"
  echo "         - \`M\` - Molecular barcode bases"
  echo "         - \`S\` - Skip bases"
  echo ""
  echo "    -u, --undetermined_sample_name"
  echo "        type: string"
  echo "        example: Undetermined"
  echo "        The sample name for undetermined reads (reads that do not match an"
  echo "        expected barcode)"
  echo ""
  echo "    -U, --most_unmatched_to_output"
  echo "        type: integer"
  echo "        example: 1000"
  echo "        Output the most frequent \"unmatched\" barcodes up to this number."
  echo "        If set to 0 unmatched barcodes will not be collected, improving overall"
  echo "        performance."
  echo ""
  echo "    --override_matcher"
  echo "        type: string"
  echo "        choices: [ cached-hamming-distance, pre-compute ]"
  echo "        If the sample barcodes are > 12 bp long, a cached hamming distance"
  echo "        matcher is used."
  echo "        If the barcodes are less than or equal to 12 bp long, all possible"
  echo "        matches are precomputed."
  echo "        This option allows for overriding that heuristic."
  echo ""
  echo "    --skip_read_name_check"
  echo "        type: boolean_true"
  echo "        If this is true, then all the read names across FASTQs will not be"
  echo "        enforced to be the same."
  echo "        This may be useful when the read names are known to be the same and"
  echo "        performance matters."
  echo "        Regardless, the first read name in each FASTQ will always be checked."
  echo ""
  echo "    --sample_barcode_in_fastq_header"
  echo "        type: boolean_true"
  echo "        If this is true, then the sample barcode is expected to be in the FASTQ"
  echo "        read header."
  echo "        For dual indexed data, the barcodes must be \`+\` (plus) delimited."
  echo "        Additionally, if true,"
  echo "        then neither index FASTQ files nor sample barcode segments in the read"
  echo "        structure may be specified."
  echo ""
  echo "    --metric_prefix"
  echo "        type: string"
  echo "        Prepend this prefix to all output metric file names"
  echo ""
  echo "    -l, --lane"
  echo "        type: integer, multiple values allowed"
  echo "        Select a subset of lanes to demultiplex.  Will cause only samples and"
  echo "        input FASTQs with"
  echo "        the given \`Lane\`(s) to be demultiplexed. Samples without a lane will be"
  echo "        ignored, and"
  echo "        FASTQs without lane information will be ignored"
}

# initialise variables
VIASH_MODE='run'
VIASH_ENGINE_ID='docker'

######## Helper functions for setting up Docker images for viash ########
# expects: ViashDockerBuild

# ViashDockerInstallationCheck: check whether Docker is installed correctly
#
# examples:
#   ViashDockerInstallationCheck
function ViashDockerInstallationCheck {
  ViashDebug "Checking whether Docker is installed"
  if [ ! command -v docker &> /dev/null ]; then
    ViashCritical "Docker doesn't seem to be installed. See 'https://docs.docker.com/get-docker/' for instructions."
    exit 1
  fi

  ViashDebug "Checking whether the Docker daemon is running"
  local save=$-; set +e
  local docker_version=$(docker version --format '{{.Client.APIVersion}}' 2> /dev/null)
  local out=$?
  [[ $save =~ e ]] && set -e
  if [ $out -ne 0 ]; then
    ViashCritical "Docker daemon does not seem to be running. Try one of the following:"
    ViashCritical "- Try running 'dockerd' in the command line"
    ViashCritical "- See https://docs.docker.com/config/daemon/"
    exit 1
  fi
}

# ViashDockerRemoteTagCheck: check whether a Docker image is available 
# on a remote. Assumes `docker login` has been performed, if relevant.
#
# $1                  : image identifier with format `[registry/]image[:tag]`
# exit code $?        : whether or not the image was found
# examples:
#   ViashDockerRemoteTagCheck python:latest
#   echo $?                                     # returns '0'
#   ViashDockerRemoteTagCheck sdaizudceahifu
#   echo $?                                     # returns '1'
function ViashDockerRemoteTagCheck {
  docker manifest inspect $1 > /dev/null 2> /dev/null
}

# ViashDockerLocalTagCheck: check whether a Docker image is available locally
#
# $1                  : image identifier with format `[registry/]image[:tag]`
# exit code $?        : whether or not the image was found
# examples:
#   docker pull python:latest
#   ViashDockerLocalTagCheck python:latest
#   echo $?                                     # returns '0'
#   ViashDockerLocalTagCheck sdaizudceahifu
#   echo $?                                     # returns '1'
function ViashDockerLocalTagCheck {
  [ -n "$(docker images -q $1)" ]
}

# ViashDockerPull: pull a Docker image
#
# $1                  : image identifier with format `[registry/]image[:tag]`
# exit code $?        : whether or not the image was found
# examples:
#   ViashDockerPull python:latest
#   echo $?                                     # returns '0'
#   ViashDockerPull sdaizudceahifu
#   echo $?                                     # returns '1'
function ViashDockerPull {
  ViashNotice "Checking if Docker image is available at '$1'"
  if [ $VIASH_VERBOSITY -ge $VIASH_LOGCODE_INFO ]; then
    docker pull $1 && return 0 || return 1
  else
    local save=$-; set +e
    docker pull $1 2> /dev/null > /dev/null
    local out=$?
    [[ $save =~ e ]] && set -e
    if [ $out -ne 0 ]; then
      ViashWarning "Could not pull from '$1'. Docker image doesn't exist or is not accessible."
    fi
    return $out
  fi
}

# ViashDockerPush: push a Docker image
#
# $1                  : image identifier with format `[registry/]image[:tag]`
# exit code $?        : whether or not the image was found
# examples:
#   ViashDockerPush python:latest
#   echo $?                                     # returns '0'
#   ViashDockerPush sdaizudceahifu
#   echo $?                                     # returns '1'
function ViashDockerPush {
  ViashNotice "Pushing image to '$1'"
  local save=$-; set +e
  local out
  if [ $VIASH_VERBOSITY -ge $VIASH_LOGCODE_INFO ]; then
    docker push $1
    out=$?
  else
    docker push $1 2> /dev/null > /dev/null
    out=$?
  fi
  [[ $save =~ e ]] && set -e
  if [ $out -eq 0 ]; then
    ViashNotice "Container '$1' push succeeded."
  else
    ViashError "Container '$1' push errored. You might not be logged in or have the necessary permissions."
  fi
  return $out
}

# ViashDockerPullElseBuild: pull a Docker image, else build it
#
# $1                  : image identifier with format `[registry/]image[:tag]`
# ViashDockerBuild    : a Bash function which builds a docker image, takes image identifier as argument.
# examples:
#   ViashDockerPullElseBuild mynewcomponent
function ViashDockerPullElseBuild {
  local save=$-; set +e
  ViashDockerPull $1
  local out=$?
  [[ $save =~ e ]] && set -e
  if [ $out -ne 0 ]; then
    ViashDockerBuild $@
  fi
}

# ViashDockerSetup: create a Docker image, according to specified docker setup strategy
#
# $1          : image identifier with format `[registry/]image[:tag]`
# $2          : docker setup strategy, see DockerSetupStrategy.scala
# examples:
#   ViashDockerSetup mynewcomponent alwaysbuild
function ViashDockerSetup {
  local image_id="$1"
  local setup_strategy="$2"
  if [ "$setup_strategy" == "alwaysbuild" -o "$setup_strategy" == "build" -o "$setup_strategy" == "b" ]; then
    ViashDockerBuild $image_id --no-cache $(ViashDockerBuildArgs "$engine_id")
  elif [ "$setup_strategy" == "alwayspull" -o "$setup_strategy" == "pull" -o "$setup_strategy" == "p" ]; then
    ViashDockerPull $image_id
  elif [ "$setup_strategy" == "alwayspullelsebuild" -o "$setup_strategy" == "pullelsebuild" ]; then
    ViashDockerPullElseBuild $image_id --no-cache $(ViashDockerBuildArgs "$engine_id")
  elif [ "$setup_strategy" == "alwayspullelsecachedbuild" -o "$setup_strategy" == "pullelsecachedbuild" ]; then
    ViashDockerPullElseBuild $image_id $(ViashDockerBuildArgs "$engine_id")
  elif [ "$setup_strategy" == "alwayscachedbuild" -o "$setup_strategy" == "cachedbuild" -o "$setup_strategy" == "cb" ]; then
    ViashDockerBuild $image_id $(ViashDockerBuildArgs "$engine_id")
  elif [[ "$setup_strategy" =~ ^ifneedbe ]]; then
    local save=$-; set +e
    ViashDockerLocalTagCheck $image_id
    local outCheck=$?
    [[ $save =~ e ]] && set -e
    if [ $outCheck -eq 0 ]; then
      ViashInfo "Image $image_id already exists"
    elif [ "$setup_strategy" == "ifneedbebuild" ]; then
      ViashDockerBuild $image_id --no-cache $(ViashDockerBuildArgs "$engine_id")
    elif [ "$setup_strategy" == "ifneedbecachedbuild" ]; then
      ViashDockerBuild $image_id $(ViashDockerBuildArgs "$engine_id")
    elif [ "$setup_strategy" == "ifneedbepull" ]; then
      ViashDockerPull $image_id
    elif [ "$setup_strategy" == "ifneedbepullelsebuild" ]; then
      ViashDockerPullElseBuild $image_id --no-cache $(ViashDockerBuildArgs "$engine_id")
    elif [ "$setup_strategy" == "ifneedbepullelsecachedbuild" ]; then
      ViashDockerPullElseBuild $image_id $(ViashDockerBuildArgs "$engine_id")
    else
      ViashError "Unrecognised Docker strategy: $setup_strategy"
      exit 1
    fi
  elif [ "$setup_strategy" == "push" -o "$setup_strategy" == "forcepush" -o "$setup_strategy" == "alwayspush" ]; then
    ViashDockerPush "$image_id"
  elif [ "$setup_strategy" == "pushifnotpresent" -o "$setup_strategy" == "gentlepush" -o "$setup_strategy" == "maybepush" ]; then
    local save=$-; set +e
    ViashDockerRemoteTagCheck $image_id
    local outCheck=$?
    [[ $save =~ e ]] && set -e
    if [ $outCheck -eq 0 ]; then
      ViashNotice "Container '$image_id' exists, doing nothing."
    else
      ViashNotice "Container '$image_id' does not yet exist."
      ViashDockerPush "$image_id"
    fi
  elif [ "$setup_strategy" == "donothing" -o "$setup_strategy" == "meh" ]; then
    ViashNotice "Skipping setup."
  else
    ViashError "Unrecognised Docker strategy: $setup_strategy"
    exit 1
  fi
}

# ViashDockerCheckCommands: Check whether a docker container has the required commands
#
# $1                  : image identifier with format `[registry/]image[:tag]`
# $@                  : commands to verify being present
# examples:
#   ViashDockerCheckCommands bash:4.0 bash ps foo
function ViashDockerCheckCommands {
  local image_id="$1"
  shift 1
  local commands="$@"
  local save=$-; set +e
  local missing # mark 'missing' as local in advance, otherwise the exit code of the command will be missing and always be '0'
  missing=$(docker run --rm --entrypoint=sh "$image_id" -c "for command in $commands; do command -v \$command >/dev/null 2>&1; if [ \$? -ne 0 ]; then echo \$command; exit 1; fi; done")
  local outCheck=$?
  [[ $save =~ e ]] && set -e
  if [ $outCheck -ne 0 ]; then
  	ViashError "Docker container '$image_id' does not contain command '$missing'."
  	exit 1
  fi
}

# ViashDockerBuild: build a docker image
# $1                               : image identifier with format `[registry/]image[:tag]`
# $...                             : additional arguments to pass to docker build
# $VIASH_META_TEMP_DIR             : temporary directory to store dockerfile & optional resources in
# $VIASH_META_NAME                 : name of the component
# $VIASH_META_RESOURCES_DIR        : directory containing the resources
# $VIASH_VERBOSITY                 : verbosity level
# exit code $?                     : whether or not the image was built successfully
function ViashDockerBuild {
  local image_id="$1"
  shift 1

  # create temporary directory to store dockerfile & optional resources in
  local tmpdir=$(mktemp -d "$VIASH_META_TEMP_DIR/dockerbuild-$VIASH_META_NAME-XXXXXX")
  local dockerfile="$tmpdir/Dockerfile"
  function clean_up {
    rm -rf "$tmpdir"
  }
  trap clean_up EXIT

  # store dockerfile and resources
  ViashDockerfile "$VIASH_ENGINE_ID" > "$dockerfile"

  # generate the build command
  local docker_build_cmd="docker build -t '$image_id' $@ '$VIASH_META_RESOURCES_DIR' -f '$dockerfile'"

  # build the container
  ViashNotice "Building container '$image_id' with Dockerfile"
  ViashInfo "$docker_build_cmd"
  local save=$-; set +e
  if [ $VIASH_VERBOSITY -ge $VIASH_LOGCODE_INFO ]; then
    eval $docker_build_cmd
  else
    eval $docker_build_cmd &> "$tmpdir/docker_build.log"
  fi

  # check exit code
  local out=$?
  [[ $save =~ e ]] && set -e
  if [ $out -ne 0 ]; then
    ViashError "Error occurred while building container '$image_id'"
    if [ $VIASH_VERBOSITY -lt $VIASH_LOGCODE_INFO ]; then
      ViashError "Transcript: --------------------------------"
      cat "$tmpdir/docker_build.log"
      ViashError "End of transcript --------------------------"
    fi
    exit 1
  fi
}

######## End of helper functions for setting up Docker images for viash ########

# ViashDockerFile: print the dockerfile to stdout
# $1    : engine identifier
# return : dockerfile required to run this component
# examples:
#   ViashDockerFile
function ViashDockerfile {
  local engine_id="$1"

  if [[ "$engine_id" == "docker" ]]; then
    cat << 'VIASHDOCKER'
FROM continuumio/miniconda3:latest
ENTRYPOINT []
RUN apt-get update && \
  DEBIAN_FRONTEND=noninteractive apt-get install -y procps && \
  rm -rf /var/lib/apt/lists/*

RUN conda install -c conda-forge -c bioconda sgdemux && \
echo "sgdemux: $(sgdemux --version | cut -d' ' -f2)" > /var/software_versions.txt

LABEL org.opencontainers.image.authors="Dries Schaumont"
LABEL org.opencontainers.image.description="Companion container for running component sgdemux"
LABEL org.opencontainers.image.created="2024-11-26T11:31:34Z"
LABEL org.opencontainers.image.source="https://github.com/Singular-Genomics/singular-demux"
LABEL org.opencontainers.image.revision="57cdff4c714136520441e853a5a746118427c65c"
LABEL org.opencontainers.image.version="add_bases2fastq"

VIASHDOCKER
  fi
}

# ViashDockerBuildArgs: return the arguments to pass to docker build
# $1    : engine identifier
# return : arguments to pass to docker build
function ViashDockerBuildArgs {
  local engine_id="$1"

  if [[ "$engine_id" == "docker" ]]; then
    echo ""
  fi
}

# ViashAbsolutePath: generate absolute path from relative path
# borrowed from https://stackoverflow.com/a/21951256
# $1     : relative filename
# return : absolute path
# examples:
#   ViashAbsolutePath some_file.txt   # returns /path/to/some_file.txt
#   ViashAbsolutePath /foo/bar/..     # returns /foo
function ViashAbsolutePath {
  local thePath
  local parr
  local outp
  local len
  if [[ ! "$1" =~ ^/ ]]; then
    thePath="$PWD/$1"
  else
    thePath="$1"
  fi
  echo "$thePath" | (
    IFS=/
    read -a parr
    declare -a outp
    for i in "${parr[@]}"; do
      case "$i" in
      ''|.) continue ;;
      ..)
        len=${#outp[@]}
        if ((len==0)); then
          continue
        else
          unset outp[$((len-1))]
        fi
        ;;
      *)
        len=${#outp[@]}
        outp[$len]="$i"
      ;;
      esac
    done
    echo /"${outp[*]}"
  )
}
# ViashDockerAutodetectMount: auto configuring docker mounts from parameters
# $1                             : The parameter value
# returns                        : New parameter
# $VIASH_DIRECTORY_MOUNTS        : Added another parameter to be passed to docker
# $VIASH_DOCKER_AUTOMOUNT_PREFIX : The prefix to be used for the automounts
# examples:
#   ViashDockerAutodetectMount /path/to/bar      # returns '/viash_automount/path/to/bar'
#   ViashDockerAutodetectMountArg /path/to/bar   # returns '--volume="/path/to:/viash_automount/path/to"'
function ViashDockerAutodetectMount {
  local abs_path=$(ViashAbsolutePath "$1")
  local mount_source
  local base_name
  if [ -d "$abs_path" ]; then
    mount_source="$abs_path"
    base_name=""
  else
    mount_source=`dirname "$abs_path"`
    base_name=`basename "$abs_path"`
  fi
  local mount_target="$VIASH_DOCKER_AUTOMOUNT_PREFIX$mount_source"
  if [ -z "$base_name" ]; then
    echo "$mount_target"
  else
    echo "$mount_target/$base_name"
  fi
}
function ViashDockerAutodetectMountArg {
  local abs_path=$(ViashAbsolutePath "$1")
  local mount_source
  local base_name
  if [ -d "$abs_path" ]; then
    mount_source="$abs_path"
    base_name=""
  else
    mount_source=`dirname "$abs_path"`
    base_name=`basename "$abs_path"`
  fi
  local mount_target="$VIASH_DOCKER_AUTOMOUNT_PREFIX$mount_source"
  ViashDebug "ViashDockerAutodetectMountArg $1 -> $mount_source -> $mount_target"
  echo "--volume=\"$mount_source:$mount_target\""
}
function ViashDockerStripAutomount {
  local abs_path=$(ViashAbsolutePath "$1")
  echo "${abs_path#$VIASH_DOCKER_AUTOMOUNT_PREFIX}"
}
# initialise variables
VIASH_DIRECTORY_MOUNTS=()

# configure default docker automount prefix if it is unset
if [ -z "${VIASH_DOCKER_AUTOMOUNT_PREFIX+x}" ]; then
  VIASH_DOCKER_AUTOMOUNT_PREFIX="/viash_automount"
fi

# initialise docker variables
VIASH_DOCKER_RUN_ARGS=(-i --rm)

# initialise array
VIASH_POSITIONAL_ARGS=''

while [[ $# -gt 0 ]]; do
    case "$1" in
        -h|--help)
            ViashHelp
            exit
            ;;
        ---v|---verbose)
            let "VIASH_VERBOSITY=VIASH_VERBOSITY+1"
            shift 1
            ;;
        ---verbosity)
            VIASH_VERBOSITY="$2"
            shift 2
            ;;
        ---verbosity=*)
            VIASH_VERBOSITY="$(ViashRemoveFlags "$1")"
            shift 1
            ;;
        --version)
            echo "sgdemux add_bases2fastq"
            exit
            ;;
        --fastqs)
            if [ -z "$VIASH_PAR_FASTQS" ]; then
              VIASH_PAR_FASTQS="$2"
            else
              VIASH_PAR_FASTQS="$VIASH_PAR_FASTQS;""$2"
            fi
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --fastqs. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --fastqs=*)
            if [ -z "$VIASH_PAR_FASTQS" ]; then
              VIASH_PAR_FASTQS=$(ViashRemoveFlags "$1")
            else
              VIASH_PAR_FASTQS="$VIASH_PAR_FASTQS;"$(ViashRemoveFlags "$1")
            fi
            shift 1
            ;;
        -f)
            if [ -z "$VIASH_PAR_FASTQS" ]; then
              VIASH_PAR_FASTQS="$2"
            else
              VIASH_PAR_FASTQS="$VIASH_PAR_FASTQS;""$2"
            fi
            [ $# -lt 2 ] && ViashError Not enough arguments passed to -f. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --sample_metadata)
            [ -n "$VIASH_PAR_SAMPLE_METADATA" ] && ViashError Bad arguments for option \'--sample_metadata\': \'$VIASH_PAR_SAMPLE_METADATA\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_SAMPLE_METADATA="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --sample_metadata. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --sample_metadata=*)
            [ -n "$VIASH_PAR_SAMPLE_METADATA" ] && ViashError Bad arguments for option \'--sample_metadata=*\': \'$VIASH_PAR_SAMPLE_METADATA\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_SAMPLE_METADATA=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        -s)
            [ -n "$VIASH_PAR_SAMPLE_METADATA" ] && ViashError Bad arguments for option \'-s\': \'$VIASH_PAR_SAMPLE_METADATA\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_SAMPLE_METADATA="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to -s. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --sample_fastq)
            [ -n "$VIASH_PAR_SAMPLE_FASTQ" ] && ViashError Bad arguments for option \'--sample_fastq\': \'$VIASH_PAR_SAMPLE_FASTQ\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_SAMPLE_FASTQ="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --sample_fastq. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --sample_fastq=*)
            [ -n "$VIASH_PAR_SAMPLE_FASTQ" ] && ViashError Bad arguments for option \'--sample_fastq=*\': \'$VIASH_PAR_SAMPLE_FASTQ\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_SAMPLE_FASTQ=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        --metrics)
            [ -n "$VIASH_PAR_METRICS" ] && ViashError Bad arguments for option \'--metrics\': \'$VIASH_PAR_METRICS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_METRICS="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --metrics. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --metrics=*)
            [ -n "$VIASH_PAR_METRICS" ] && ViashError Bad arguments for option \'--metrics=*\': \'$VIASH_PAR_METRICS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_METRICS=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        --most_frequent_unmatched)
            [ -n "$VIASH_PAR_MOST_FREQUENT_UNMATCHED" ] && ViashError Bad arguments for option \'--most_frequent_unmatched\': \'$VIASH_PAR_MOST_FREQUENT_UNMATCHED\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_MOST_FREQUENT_UNMATCHED="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --most_frequent_unmatched. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --most_frequent_unmatched=*)
            [ -n "$VIASH_PAR_MOST_FREQUENT_UNMATCHED" ] && ViashError Bad arguments for option \'--most_frequent_unmatched=*\': \'$VIASH_PAR_MOST_FREQUENT_UNMATCHED\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_MOST_FREQUENT_UNMATCHED=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        --sample_barcode_hop_metrics)
            [ -n "$VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS" ] && ViashError Bad arguments for option \'--sample_barcode_hop_metrics\': \'$VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --sample_barcode_hop_metrics. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --sample_barcode_hop_metrics=*)
            [ -n "$VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS" ] && ViashError Bad arguments for option \'--sample_barcode_hop_metrics=*\': \'$VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        --per_project_metrics)
            [ -n "$VIASH_PAR_PER_PROJECT_METRICS" ] && ViashError Bad arguments for option \'--per_project_metrics\': \'$VIASH_PAR_PER_PROJECT_METRICS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_PER_PROJECT_METRICS="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --per_project_metrics. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --per_project_metrics=*)
            [ -n "$VIASH_PAR_PER_PROJECT_METRICS" ] && ViashError Bad arguments for option \'--per_project_metrics=*\': \'$VIASH_PAR_PER_PROJECT_METRICS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_PER_PROJECT_METRICS=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        --per_sample_metrics)
            [ -n "$VIASH_PAR_PER_SAMPLE_METRICS" ] && ViashError Bad arguments for option \'--per_sample_metrics\': \'$VIASH_PAR_PER_SAMPLE_METRICS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_PER_SAMPLE_METRICS="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --per_sample_metrics. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --per_sample_metrics=*)
            [ -n "$VIASH_PAR_PER_SAMPLE_METRICS" ] && ViashError Bad arguments for option \'--per_sample_metrics=*\': \'$VIASH_PAR_PER_SAMPLE_METRICS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_PER_SAMPLE_METRICS=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        --read_structures)
            if [ -z "$VIASH_PAR_READ_STRUCTURES" ]; then
              VIASH_PAR_READ_STRUCTURES="$2"
            else
              VIASH_PAR_READ_STRUCTURES="$VIASH_PAR_READ_STRUCTURES;""$2"
            fi
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --read_structures. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --read_structures=*)
            if [ -z "$VIASH_PAR_READ_STRUCTURES" ]; then
              VIASH_PAR_READ_STRUCTURES=$(ViashRemoveFlags "$1")
            else
              VIASH_PAR_READ_STRUCTURES="$VIASH_PAR_READ_STRUCTURES;"$(ViashRemoveFlags "$1")
            fi
            shift 1
            ;;
        -r)
            if [ -z "$VIASH_PAR_READ_STRUCTURES" ]; then
              VIASH_PAR_READ_STRUCTURES="$2"
            else
              VIASH_PAR_READ_STRUCTURES="$VIASH_PAR_READ_STRUCTURES;""$2"
            fi
            [ $# -lt 2 ] && ViashError Not enough arguments passed to -r. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --allowed_mismatches)
            [ -n "$VIASH_PAR_ALLOWED_MISMATCHES" ] && ViashError Bad arguments for option \'--allowed_mismatches\': \'$VIASH_PAR_ALLOWED_MISMATCHES\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_ALLOWED_MISMATCHES="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --allowed_mismatches. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --allowed_mismatches=*)
            [ -n "$VIASH_PAR_ALLOWED_MISMATCHES" ] && ViashError Bad arguments for option \'--allowed_mismatches=*\': \'$VIASH_PAR_ALLOWED_MISMATCHES\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_ALLOWED_MISMATCHES=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        -m)
            [ -n "$VIASH_PAR_ALLOWED_MISMATCHES" ] && ViashError Bad arguments for option \'-m\': \'$VIASH_PAR_ALLOWED_MISMATCHES\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_ALLOWED_MISMATCHES="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to -m. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --min_delta)
            [ -n "$VIASH_PAR_MIN_DELTA" ] && ViashError Bad arguments for option \'--min_delta\': \'$VIASH_PAR_MIN_DELTA\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_MIN_DELTA="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --min_delta. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --min_delta=*)
            [ -n "$VIASH_PAR_MIN_DELTA" ] && ViashError Bad arguments for option \'--min_delta=*\': \'$VIASH_PAR_MIN_DELTA\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_MIN_DELTA=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        -d)
            [ -n "$VIASH_PAR_MIN_DELTA" ] && ViashError Bad arguments for option \'-d\': \'$VIASH_PAR_MIN_DELTA\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_MIN_DELTA="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to -d. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --free_ns)
            [ -n "$VIASH_PAR_FREE_NS" ] && ViashError Bad arguments for option \'--free_ns\': \'$VIASH_PAR_FREE_NS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_FREE_NS="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --free_ns. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --free_ns=*)
            [ -n "$VIASH_PAR_FREE_NS" ] && ViashError Bad arguments for option \'--free_ns=*\': \'$VIASH_PAR_FREE_NS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_FREE_NS=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        -F)
            [ -n "$VIASH_PAR_FREE_NS" ] && ViashError Bad arguments for option \'-F\': \'$VIASH_PAR_FREE_NS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_FREE_NS="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to -F. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --max_no_calls)
            [ -n "$VIASH_PAR_MAX_NO_CALLS" ] && ViashError Bad arguments for option \'--max_no_calls\': \'$VIASH_PAR_MAX_NO_CALLS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_MAX_NO_CALLS="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --max_no_calls. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --max_no_calls=*)
            [ -n "$VIASH_PAR_MAX_NO_CALLS" ] && ViashError Bad arguments for option \'--max_no_calls=*\': \'$VIASH_PAR_MAX_NO_CALLS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_MAX_NO_CALLS=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        -N)
            [ -n "$VIASH_PAR_MAX_NO_CALLS" ] && ViashError Bad arguments for option \'-N\': \'$VIASH_PAR_MAX_NO_CALLS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_MAX_NO_CALLS="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to -N. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --quality_mask_threshold)
            if [ -z "$VIASH_PAR_QUALITY_MASK_THRESHOLD" ]; then
              VIASH_PAR_QUALITY_MASK_THRESHOLD="$2"
            else
              VIASH_PAR_QUALITY_MASK_THRESHOLD="$VIASH_PAR_QUALITY_MASK_THRESHOLD;""$2"
            fi
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --quality_mask_threshold. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --quality_mask_threshold=*)
            if [ -z "$VIASH_PAR_QUALITY_MASK_THRESHOLD" ]; then
              VIASH_PAR_QUALITY_MASK_THRESHOLD=$(ViashRemoveFlags "$1")
            else
              VIASH_PAR_QUALITY_MASK_THRESHOLD="$VIASH_PAR_QUALITY_MASK_THRESHOLD;"$(ViashRemoveFlags "$1")
            fi
            shift 1
            ;;
        -M)
            if [ -z "$VIASH_PAR_QUALITY_MASK_THRESHOLD" ]; then
              VIASH_PAR_QUALITY_MASK_THRESHOLD="$2"
            else
              VIASH_PAR_QUALITY_MASK_THRESHOLD="$VIASH_PAR_QUALITY_MASK_THRESHOLD;""$2"
            fi
            [ $# -lt 2 ] && ViashError Not enough arguments passed to -M. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --filter_control_reads)
            [ -n "$VIASH_PAR_FILTER_CONTROL_READS" ] && ViashError Bad arguments for option \'--filter_control_reads\': \'$VIASH_PAR_FILTER_CONTROL_READS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_FILTER_CONTROL_READS=true
            shift 1
            ;;
        -C)
            [ -n "$VIASH_PAR_FILTER_CONTROL_READS" ] && ViashError Bad arguments for option \'-C\': \'$VIASH_PAR_FILTER_CONTROL_READS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_FILTER_CONTROL_READS=true
            shift 1
            ;;
        --filter_failing_quality)
            [ -n "$VIASH_PAR_FILTER_FAILING_QUALITY" ] && ViashError Bad arguments for option \'--filter_failing_quality\': \'$VIASH_PAR_FILTER_FAILING_QUALITY\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_FILTER_FAILING_QUALITY=true
            shift 1
            ;;
        -Q)
            [ -n "$VIASH_PAR_FILTER_FAILING_QUALITY" ] && ViashError Bad arguments for option \'-Q\': \'$VIASH_PAR_FILTER_FAILING_QUALITY\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_FILTER_FAILING_QUALITY=true
            shift 1
            ;;
        --output_types)
            if [ -z "$VIASH_PAR_OUTPUT_TYPES" ]; then
              VIASH_PAR_OUTPUT_TYPES="$2"
            else
              VIASH_PAR_OUTPUT_TYPES="$VIASH_PAR_OUTPUT_TYPES;""$2"
            fi
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --output_types. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --output_types=*)
            if [ -z "$VIASH_PAR_OUTPUT_TYPES" ]; then
              VIASH_PAR_OUTPUT_TYPES=$(ViashRemoveFlags "$1")
            else
              VIASH_PAR_OUTPUT_TYPES="$VIASH_PAR_OUTPUT_TYPES;"$(ViashRemoveFlags "$1")
            fi
            shift 1
            ;;
        -T)
            if [ -z "$VIASH_PAR_OUTPUT_TYPES" ]; then
              VIASH_PAR_OUTPUT_TYPES="$2"
            else
              VIASH_PAR_OUTPUT_TYPES="$VIASH_PAR_OUTPUT_TYPES;""$2"
            fi
            [ $# -lt 2 ] && ViashError Not enough arguments passed to -T. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --undetermined_sample_name)
            [ -n "$VIASH_PAR_UNDETERMINED_SAMPLE_NAME" ] && ViashError Bad arguments for option \'--undetermined_sample_name\': \'$VIASH_PAR_UNDETERMINED_SAMPLE_NAME\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_UNDETERMINED_SAMPLE_NAME="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --undetermined_sample_name. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --undetermined_sample_name=*)
            [ -n "$VIASH_PAR_UNDETERMINED_SAMPLE_NAME" ] && ViashError Bad arguments for option \'--undetermined_sample_name=*\': \'$VIASH_PAR_UNDETERMINED_SAMPLE_NAME\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_UNDETERMINED_SAMPLE_NAME=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        -u)
            [ -n "$VIASH_PAR_UNDETERMINED_SAMPLE_NAME" ] && ViashError Bad arguments for option \'-u\': \'$VIASH_PAR_UNDETERMINED_SAMPLE_NAME\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_UNDETERMINED_SAMPLE_NAME="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to -u. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --most_unmatched_to_output)
            [ -n "$VIASH_PAR_MOST_UNMATCHED_TO_OUTPUT" ] && ViashError Bad arguments for option \'--most_unmatched_to_output\': \'$VIASH_PAR_MOST_UNMATCHED_TO_OUTPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_MOST_UNMATCHED_TO_OUTPUT="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --most_unmatched_to_output. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --most_unmatched_to_output=*)
            [ -n "$VIASH_PAR_MOST_UNMATCHED_TO_OUTPUT" ] && ViashError Bad arguments for option \'--most_unmatched_to_output=*\': \'$VIASH_PAR_MOST_UNMATCHED_TO_OUTPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_MOST_UNMATCHED_TO_OUTPUT=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        -U)
            [ -n "$VIASH_PAR_MOST_UNMATCHED_TO_OUTPUT" ] && ViashError Bad arguments for option \'-U\': \'$VIASH_PAR_MOST_UNMATCHED_TO_OUTPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_MOST_UNMATCHED_TO_OUTPUT="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to -U. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --override_matcher)
            [ -n "$VIASH_PAR_OVERRIDE_MATCHER" ] && ViashError Bad arguments for option \'--override_matcher\': \'$VIASH_PAR_OVERRIDE_MATCHER\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_OVERRIDE_MATCHER="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --override_matcher. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --override_matcher=*)
            [ -n "$VIASH_PAR_OVERRIDE_MATCHER" ] && ViashError Bad arguments for option \'--override_matcher=*\': \'$VIASH_PAR_OVERRIDE_MATCHER\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_OVERRIDE_MATCHER=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        --skip_read_name_check)
            [ -n "$VIASH_PAR_SKIP_READ_NAME_CHECK" ] && ViashError Bad arguments for option \'--skip_read_name_check\': \'$VIASH_PAR_SKIP_READ_NAME_CHECK\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_SKIP_READ_NAME_CHECK=true
            shift 1
            ;;
        --sample_barcode_in_fastq_header)
            [ -n "$VIASH_PAR_SAMPLE_BARCODE_IN_FASTQ_HEADER" ] && ViashError Bad arguments for option \'--sample_barcode_in_fastq_header\': \'$VIASH_PAR_SAMPLE_BARCODE_IN_FASTQ_HEADER\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_SAMPLE_BARCODE_IN_FASTQ_HEADER=true
            shift 1
            ;;
        --metric_prefix)
            [ -n "$VIASH_PAR_METRIC_PREFIX" ] && ViashError Bad arguments for option \'--metric_prefix\': \'$VIASH_PAR_METRIC_PREFIX\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_METRIC_PREFIX="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --metric_prefix. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --metric_prefix=*)
            [ -n "$VIASH_PAR_METRIC_PREFIX" ] && ViashError Bad arguments for option \'--metric_prefix=*\': \'$VIASH_PAR_METRIC_PREFIX\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_METRIC_PREFIX=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        --lane)
            if [ -z "$VIASH_PAR_LANE" ]; then
              VIASH_PAR_LANE="$2"
            else
              VIASH_PAR_LANE="$VIASH_PAR_LANE;""$2"
            fi
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --lane. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --lane=*)
            if [ -z "$VIASH_PAR_LANE" ]; then
              VIASH_PAR_LANE=$(ViashRemoveFlags "$1")
            else
              VIASH_PAR_LANE="$VIASH_PAR_LANE;"$(ViashRemoveFlags "$1")
            fi
            shift 1
            ;;
        -l)
            if [ -z "$VIASH_PAR_LANE" ]; then
              VIASH_PAR_LANE="$2"
            else
              VIASH_PAR_LANE="$VIASH_PAR_LANE;""$2"
            fi
            [ $# -lt 2 ] && ViashError Not enough arguments passed to -l. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        ---engine)
            VIASH_ENGINE_ID="$2"
            shift 2
            ;;
        ---engine=*)
            VIASH_ENGINE_ID="$(ViashRemoveFlags "$1")"
            shift 1
            ;;
        ---setup)
            VIASH_MODE='setup'
            VIASH_SETUP_STRATEGY="$2"
            shift 2
            ;;
        ---setup=*)
            VIASH_MODE='setup'
            VIASH_SETUP_STRATEGY="$(ViashRemoveFlags "$1")"
            shift 1
            ;;
        ---dockerfile)
            VIASH_MODE='dockerfile'
            shift 1
            ;;
        ---docker_run_args)
            VIASH_DOCKER_RUN_ARGS+=("$2")
            shift 2
            ;;
        ---docker_run_args=*)
            VIASH_DOCKER_RUN_ARGS+=("$(ViashRemoveFlags "$1")")
            shift 1
            ;;
        ---docker_image_id)
            VIASH_MODE='docker_image_id'
            shift 1
            ;;
        ---debug)
            VIASH_MODE='debug'
            shift 1
            ;;
        ---cpus)
            [ -n "$VIASH_META_CPUS" ] && ViashError Bad arguments for option \'---cpus\': \'$VIASH_META_CPUS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_META_CPUS="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to ---cpus. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        ---cpus=*)
            [ -n "$VIASH_META_CPUS" ] && ViashError Bad arguments for option \'---cpus=*\': \'$VIASH_META_CPUS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_META_CPUS=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        ---memory)
            [ -n "$VIASH_META_MEMORY" ] && ViashError Bad arguments for option \'---memory\': \'$VIASH_META_MEMORY\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_META_MEMORY="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to ---memory. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        ---memory=*)
            [ -n "$VIASH_META_MEMORY" ] && ViashError Bad arguments for option \'---memory=*\': \'$VIASH_META_MEMORY\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_META_MEMORY=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        *)  # positional arg or unknown option
            # since the positional args will be eval'd, can we always quote, instead of using ViashQuote
            VIASH_POSITIONAL_ARGS="$VIASH_POSITIONAL_ARGS '$1'"
            [[ $1 == -* ]] && ViashWarning $1 looks like a parameter but is not a defined parameter and will instead be treated as a positional argument. Use "--help" to get more information on the parameters.
            shift # past argument
            ;;
    esac
done

# parse positional parameters
eval set -- $VIASH_POSITIONAL_ARGS


if   [ "$VIASH_ENGINE_ID" == "native" ]  ; then
  VIASH_ENGINE_TYPE='native'
elif   [ "$VIASH_ENGINE_ID" == "docker" ]  ; then
  VIASH_ENGINE_TYPE='docker'
else
  ViashError "Engine '$VIASH_ENGINE_ID' is not recognized. Options are: docker, native."
  exit 1
fi

if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then
  # check if docker is installed properly
  ViashDockerInstallationCheck

  # determine docker image id
  if [[ "$VIASH_ENGINE_ID" == 'docker' ]]; then
    VIASH_DOCKER_IMAGE_ID='images.viash-hub.com/vsh/biobox/sgdemux:add_bases2fastq'
  fi

  # print dockerfile
  if [ "$VIASH_MODE" == "dockerfile" ]; then
    ViashDockerfile "$VIASH_ENGINE_ID"
    exit 0

  elif [ "$VIASH_MODE" == "docker_image_id" ]; then
    echo "$VIASH_DOCKER_IMAGE_ID"
    exit 0
  
  # enter docker container
  elif [[ "$VIASH_MODE" == "debug" ]]; then
    VIASH_CMD="docker run --entrypoint=bash ${VIASH_DOCKER_RUN_ARGS[@]} -v '$(pwd)':/pwd --workdir /pwd -t $VIASH_DOCKER_IMAGE_ID"
    ViashNotice "+ $VIASH_CMD"
    eval $VIASH_CMD
    exit 

  # build docker image
  elif [ "$VIASH_MODE" == "setup" ]; then
    ViashDockerSetup "$VIASH_DOCKER_IMAGE_ID" "$VIASH_SETUP_STRATEGY"
    ViashDockerCheckCommands "$VIASH_DOCKER_IMAGE_ID" 'ps' 'bash'
    exit 0
  fi

  # check if docker image exists
  ViashDockerSetup "$VIASH_DOCKER_IMAGE_ID" ifneedbepullelsecachedbuild
  ViashDockerCheckCommands "$VIASH_DOCKER_IMAGE_ID" 'ps' 'bash'
fi

# setting computational defaults

# helper function for parsing memory strings
function ViashMemoryAsBytes {
  local memory=`echo "$1" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]'`
  local memory_regex='^([0-9]+)([kmgtp]i?b?|b)$'
  if [[ $memory =~ $memory_regex ]]; then
    local number=${memory/[^0-9]*/}
    local symbol=${memory/*[0-9]/}
    
    case $symbol in
      b)      memory_b=$number ;;
      kb|k)   memory_b=$(( $number * 1000 )) ;;
      mb|m)   memory_b=$(( $number * 1000 * 1000 )) ;;
      gb|g)   memory_b=$(( $number * 1000 * 1000 * 1000 )) ;;
      tb|t)   memory_b=$(( $number * 1000 * 1000 * 1000 * 1000 )) ;;
      pb|p)   memory_b=$(( $number * 1000 * 1000 * 1000 * 1000 * 1000 )) ;;
      kib|ki)   memory_b=$(( $number * 1024 )) ;;
      mib|mi)   memory_b=$(( $number * 1024 * 1024 )) ;;
      gib|gi)   memory_b=$(( $number * 1024 * 1024 * 1024 )) ;;
      tib|ti)   memory_b=$(( $number * 1024 * 1024 * 1024 * 1024 )) ;;
      pib|pi)   memory_b=$(( $number * 1024 * 1024 * 1024 * 1024 * 1024 )) ;;
    esac
    echo "$memory_b"
  fi
}
# compute memory in different units
if [ ! -z ${VIASH_META_MEMORY+x} ]; then
  VIASH_META_MEMORY_B=`ViashMemoryAsBytes $VIASH_META_MEMORY`
  # do not define other variables if memory_b is an empty string
  if [ ! -z "$VIASH_META_MEMORY_B" ]; then
    VIASH_META_MEMORY_KB=$(( ($VIASH_META_MEMORY_B+999) / 1000 ))
    VIASH_META_MEMORY_MB=$(( ($VIASH_META_MEMORY_KB+999) / 1000 ))
    VIASH_META_MEMORY_GB=$(( ($VIASH_META_MEMORY_MB+999) / 1000 ))
    VIASH_META_MEMORY_TB=$(( ($VIASH_META_MEMORY_GB+999) / 1000 ))
    VIASH_META_MEMORY_PB=$(( ($VIASH_META_MEMORY_TB+999) / 1000 ))
    VIASH_META_MEMORY_KIB=$(( ($VIASH_META_MEMORY_B+1023) / 1024 ))
    VIASH_META_MEMORY_MIB=$(( ($VIASH_META_MEMORY_KIB+1023) / 1024 ))
    VIASH_META_MEMORY_GIB=$(( ($VIASH_META_MEMORY_MIB+1023) / 1024 ))
    VIASH_META_MEMORY_TIB=$(( ($VIASH_META_MEMORY_GIB+1023) / 1024 ))
    VIASH_META_MEMORY_PIB=$(( ($VIASH_META_MEMORY_TIB+1023) / 1024 ))
  else
    # unset memory if string is empty
    unset $VIASH_META_MEMORY_B
  fi
fi
# unset nproc if string is empty
if [ -z "$VIASH_META_CPUS" ]; then
  unset $VIASH_META_CPUS
fi


# check whether required parameters exist
if [ -z ${VIASH_PAR_FASTQS+x} ]; then
  ViashError '--fastqs' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_PAR_SAMPLE_METADATA+x} ]; then
  ViashError '--sample_metadata' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_PAR_SAMPLE_FASTQ+x} ]; then
  ViashError '--sample_fastq' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_META_NAME+x} ]; then
  ViashError 'name' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_META_FUNCTIONALITY_NAME+x} ]; then
  ViashError 'functionality_name' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_META_RESOURCES_DIR+x} ]; then
  ViashError 'resources_dir' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_META_EXECUTABLE+x} ]; then
  ViashError 'executable' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_META_CONFIG+x} ]; then
  ViashError 'config' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_META_TEMP_DIR+x} ]; then
  ViashError 'temp_dir' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi

# filling in defaults
if [ -z ${VIASH_PAR_FILTER_CONTROL_READS+x} ]; then
  VIASH_PAR_FILTER_CONTROL_READS="false"
fi
if [ -z ${VIASH_PAR_FILTER_FAILING_QUALITY+x} ]; then
  VIASH_PAR_FILTER_FAILING_QUALITY="false"
fi
if [ -z ${VIASH_PAR_SKIP_READ_NAME_CHECK+x} ]; then
  VIASH_PAR_SKIP_READ_NAME_CHECK="false"
fi
if [ -z ${VIASH_PAR_SAMPLE_BARCODE_IN_FASTQ_HEADER+x} ]; then
  VIASH_PAR_SAMPLE_BARCODE_IN_FASTQ_HEADER="false"
fi

# check whether required files exist
if [ ! -z "$VIASH_PAR_FASTQS" ]; then
  IFS=';'
  set -f
  for file in $VIASH_PAR_FASTQS; do
    unset IFS
    if [ ! -e "$file" ]; then
      ViashError "Input file '$file' does not exist."
      exit 1
    fi
  done
  set +f
fi
if [ ! -z "$VIASH_PAR_SAMPLE_METADATA" ] && [ ! -e "$VIASH_PAR_SAMPLE_METADATA" ]; then
  ViashError "Input file '$VIASH_PAR_SAMPLE_METADATA' does not exist."
  exit 1
fi

# check whether parameters values are of the right type
if [[ -n "$VIASH_PAR_ALLOWED_MISMATCHES" ]]; then
  if ! [[ "$VIASH_PAR_ALLOWED_MISMATCHES" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError '--allowed_mismatches' has to be an integer. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_PAR_MIN_DELTA" ]]; then
  if ! [[ "$VIASH_PAR_MIN_DELTA" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError '--min_delta' has to be an integer. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_PAR_FREE_NS" ]]; then
  if ! [[ "$VIASH_PAR_FREE_NS" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError '--free_ns' has to be an integer. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_PAR_MAX_NO_CALLS" ]]; then
  if ! [[ "$VIASH_PAR_MAX_NO_CALLS" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError '--max_no_calls' has to be an integer. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [ -n "$VIASH_PAR_QUALITY_MASK_THRESHOLD" ]; then
  IFS=';'
  set -f
  for val in $VIASH_PAR_QUALITY_MASK_THRESHOLD; do
    if ! [[ "${val}" =~ ^[-+]?[0-9]+$ ]]; then
      ViashError '--quality_mask_threshold' has to be an integer. Use "--help" to get more information on the parameters.
      exit 1
    fi
  done
  set +f
  unset IFS
fi

if [[ -n "$VIASH_PAR_FILTER_CONTROL_READS" ]]; then
  if ! [[ "$VIASH_PAR_FILTER_CONTROL_READS" =~ ^(true|True|TRUE|false|False|FALSE|yes|Yes|YES|no|No|NO)$ ]]; then
    ViashError '--filter_control_reads' has to be a boolean_true. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_PAR_FILTER_FAILING_QUALITY" ]]; then
  if ! [[ "$VIASH_PAR_FILTER_FAILING_QUALITY" =~ ^(true|True|TRUE|false|False|FALSE|yes|Yes|YES|no|No|NO)$ ]]; then
    ViashError '--filter_failing_quality' has to be a boolean_true. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_PAR_MOST_UNMATCHED_TO_OUTPUT" ]]; then
  if ! [[ "$VIASH_PAR_MOST_UNMATCHED_TO_OUTPUT" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError '--most_unmatched_to_output' has to be an integer. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_PAR_SKIP_READ_NAME_CHECK" ]]; then
  if ! [[ "$VIASH_PAR_SKIP_READ_NAME_CHECK" =~ ^(true|True|TRUE|false|False|FALSE|yes|Yes|YES|no|No|NO)$ ]]; then
    ViashError '--skip_read_name_check' has to be a boolean_true. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_PAR_SAMPLE_BARCODE_IN_FASTQ_HEADER" ]]; then
  if ! [[ "$VIASH_PAR_SAMPLE_BARCODE_IN_FASTQ_HEADER" =~ ^(true|True|TRUE|false|False|FALSE|yes|Yes|YES|no|No|NO)$ ]]; then
    ViashError '--sample_barcode_in_fastq_header' has to be a boolean_true. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [ -n "$VIASH_PAR_LANE" ]; then
  IFS=';'
  set -f
  for val in $VIASH_PAR_LANE; do
    if ! [[ "${val}" =~ ^[-+]?[0-9]+$ ]]; then
      ViashError '--lane' has to be an integer. Use "--help" to get more information on the parameters.
      exit 1
    fi
  done
  set +f
  unset IFS
fi

if [[ -n "$VIASH_META_CPUS" ]]; then
  if ! [[ "$VIASH_META_CPUS" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'cpus' has to be an integer. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_B" ]]; then
  if ! [[ "$VIASH_META_MEMORY_B" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_b' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_KB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_KB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_kb' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_MB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_MB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_mb' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_GB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_GB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_gb' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_TB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_TB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_tb' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_PB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_PB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_pb' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_KIB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_KIB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_kib' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_MIB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_MIB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_mib' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_GIB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_GIB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_gib' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_TIB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_TIB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_tib' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_PIB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_PIB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_pib' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi

# check whether value is belongs to a set of choices
if [ ! -z "$VIASH_PAR_OUTPUT_TYPES" ]; then
  VIASH_PAR_OUTPUT_TYPES_CHOICES=("T;B;S;M")
  IFS=';'
  set -f
  for val in $VIASH_PAR_OUTPUT_TYPES; do
    if ! [[ ";${VIASH_PAR_OUTPUT_TYPES_CHOICES[*]};" =~ ";${val};" ]]; then
      ViashError '--output_types' specified value of \'${val}\' is not in the list of allowed values. Use "--help" to get more information on the parameters.
      exit 1
    fi
  done
  set +f
  unset IFS
fi

if [ ! -z "$VIASH_PAR_OVERRIDE_MATCHER" ]; then
  VIASH_PAR_OVERRIDE_MATCHER_CHOICES=("cached-hamming-distance;pre-compute")
  IFS=';'
  set -f
  if ! [[ ";${VIASH_PAR_OVERRIDE_MATCHER_CHOICES[*]};" =~ ";$VIASH_PAR_OVERRIDE_MATCHER;" ]]; then
    ViashError '--override_matcher' specified value of \'$VIASH_PAR_OVERRIDE_MATCHER\' is not in the list of allowed values. Use "--help" to get more information on the parameters.
    exit 1
  fi
  set +f
  unset IFS
fi

# create parent directories of output files, if so desired
if [ ! -z "$VIASH_PAR_SAMPLE_FASTQ" ] && [ ! -d "$(dirname "$VIASH_PAR_SAMPLE_FASTQ")" ]; then
  mkdir -p "$(dirname "$VIASH_PAR_SAMPLE_FASTQ")"
fi
if [ ! -z "$VIASH_PAR_METRICS" ] && [ ! -d "$(dirname "$VIASH_PAR_METRICS")" ]; then
  mkdir -p "$(dirname "$VIASH_PAR_METRICS")"
fi
if [ ! -z "$VIASH_PAR_MOST_FREQUENT_UNMATCHED" ] && [ ! -d "$(dirname "$VIASH_PAR_MOST_FREQUENT_UNMATCHED")" ]; then
  mkdir -p "$(dirname "$VIASH_PAR_MOST_FREQUENT_UNMATCHED")"
fi
if [ ! -z "$VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS" ] && [ ! -d "$(dirname "$VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS")" ]; then
  mkdir -p "$(dirname "$VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS")"
fi
if [ ! -z "$VIASH_PAR_PER_PROJECT_METRICS" ] && [ ! -d "$(dirname "$VIASH_PAR_PER_PROJECT_METRICS")" ]; then
  mkdir -p "$(dirname "$VIASH_PAR_PER_PROJECT_METRICS")"
fi
if [ ! -z "$VIASH_PAR_PER_SAMPLE_METRICS" ] && [ ! -d "$(dirname "$VIASH_PAR_PER_SAMPLE_METRICS")" ]; then
  mkdir -p "$(dirname "$VIASH_PAR_PER_SAMPLE_METRICS")"
fi

if  [ "$VIASH_ENGINE_ID" == "native" ]  ; then
  if [ "$VIASH_MODE" == "run" ]; then
    VIASH_CMD="bash"
  else
    ViashError "Engine '$VIASH_ENGINE_ID' does not support mode '$VIASH_MODE'."
    exit 1
  fi
fi

if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then
  # detect volumes from file arguments
  VIASH_CHOWN_VARS=()
if [ ! -z "$VIASH_PAR_FASTQS" ]; then
  VIASH_TEST_FASTQS=()
  IFS=';'
  for var in $VIASH_PAR_FASTQS; do
    unset IFS
    VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$var")" )
    var=$(ViashDockerAutodetectMount "$var")
    VIASH_TEST_FASTQS+=( "$var" )
  done
  VIASH_PAR_FASTQS=$(IFS=';' ; echo "${VIASH_TEST_FASTQS[*]}")
fi
if [ ! -z "$VIASH_PAR_SAMPLE_METADATA" ]; then
  VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_PAR_SAMPLE_METADATA")" )
  VIASH_PAR_SAMPLE_METADATA=$(ViashDockerAutodetectMount "$VIASH_PAR_SAMPLE_METADATA")
fi
if [ ! -z "$VIASH_PAR_SAMPLE_FASTQ" ]; then
  VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_PAR_SAMPLE_FASTQ")" )
  VIASH_PAR_SAMPLE_FASTQ=$(ViashDockerAutodetectMount "$VIASH_PAR_SAMPLE_FASTQ")
  VIASH_CHOWN_VARS+=( "$VIASH_PAR_SAMPLE_FASTQ" )
fi
if [ ! -z "$VIASH_PAR_METRICS" ]; then
  VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_PAR_METRICS")" )
  VIASH_PAR_METRICS=$(ViashDockerAutodetectMount "$VIASH_PAR_METRICS")
  VIASH_CHOWN_VARS+=( "$VIASH_PAR_METRICS" )
fi
if [ ! -z "$VIASH_PAR_MOST_FREQUENT_UNMATCHED" ]; then
  VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_PAR_MOST_FREQUENT_UNMATCHED")" )
  VIASH_PAR_MOST_FREQUENT_UNMATCHED=$(ViashDockerAutodetectMount "$VIASH_PAR_MOST_FREQUENT_UNMATCHED")
  VIASH_CHOWN_VARS+=( "$VIASH_PAR_MOST_FREQUENT_UNMATCHED" )
fi
if [ ! -z "$VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS" ]; then
  VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS")" )
  VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS=$(ViashDockerAutodetectMount "$VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS")
  VIASH_CHOWN_VARS+=( "$VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS" )
fi
if [ ! -z "$VIASH_PAR_PER_PROJECT_METRICS" ]; then
  VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_PAR_PER_PROJECT_METRICS")" )
  VIASH_PAR_PER_PROJECT_METRICS=$(ViashDockerAutodetectMount "$VIASH_PAR_PER_PROJECT_METRICS")
  VIASH_CHOWN_VARS+=( "$VIASH_PAR_PER_PROJECT_METRICS" )
fi
if [ ! -z "$VIASH_PAR_PER_SAMPLE_METRICS" ]; then
  VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_PAR_PER_SAMPLE_METRICS")" )
  VIASH_PAR_PER_SAMPLE_METRICS=$(ViashDockerAutodetectMount "$VIASH_PAR_PER_SAMPLE_METRICS")
  VIASH_CHOWN_VARS+=( "$VIASH_PAR_PER_SAMPLE_METRICS" )
fi
if [ ! -z "$VIASH_META_RESOURCES_DIR" ]; then
  VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_META_RESOURCES_DIR")" )
  VIASH_META_RESOURCES_DIR=$(ViashDockerAutodetectMount "$VIASH_META_RESOURCES_DIR")
fi
if [ ! -z "$VIASH_META_EXECUTABLE" ]; then
  VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_META_EXECUTABLE")" )
  VIASH_META_EXECUTABLE=$(ViashDockerAutodetectMount "$VIASH_META_EXECUTABLE")
fi
if [ ! -z "$VIASH_META_CONFIG" ]; then
  VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_META_CONFIG")" )
  VIASH_META_CONFIG=$(ViashDockerAutodetectMount "$VIASH_META_CONFIG")
fi
if [ ! -z "$VIASH_META_TEMP_DIR" ]; then
  VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_META_TEMP_DIR")" )
  VIASH_META_TEMP_DIR=$(ViashDockerAutodetectMount "$VIASH_META_TEMP_DIR")
fi
  
  # get unique mounts
  VIASH_UNIQUE_MOUNTS=($(for val in "${VIASH_DIRECTORY_MOUNTS[@]}"; do echo "$val"; done | sort -u))
fi

if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then
  # change file ownership
  function ViashPerformChown {
    if (( ${#VIASH_CHOWN_VARS[@]} )); then
      set +e
      VIASH_CMD="docker run --entrypoint=bash --rm ${VIASH_UNIQUE_MOUNTS[@]} $VIASH_DOCKER_IMAGE_ID -c 'chown $(id -u):$(id -g) --silent --recursive ${VIASH_CHOWN_VARS[@]}'"
      ViashDebug "+ $VIASH_CMD"
      eval $VIASH_CMD
      set -e
    fi
  }
  trap ViashPerformChown EXIT
fi

if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then
  # helper function for filling in extra docker args
  if [ ! -z "$VIASH_META_MEMORY_B" ]; then
    VIASH_DOCKER_RUN_ARGS+=("--memory=${VIASH_META_MEMORY_B}")
  fi
  if [ ! -z "$VIASH_META_CPUS" ]; then
    VIASH_DOCKER_RUN_ARGS+=("--cpus=${VIASH_META_CPUS}")
  fi
fi

if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then
  VIASH_CMD="docker run --entrypoint=bash ${VIASH_DOCKER_RUN_ARGS[@]} ${VIASH_UNIQUE_MOUNTS[@]} $VIASH_DOCKER_IMAGE_ID"
fi


# set dependency paths


ViashDebug "Running command: $(echo $VIASH_CMD)"
cat << VIASHEOF | eval $VIASH_CMD
set -e
tempscript=\$(mktemp "$VIASH_META_TEMP_DIR/viash-run-sgdemux-XXXXXX").sh
function clean_up {
  rm "\$tempscript"
}
function interrupt {
  echo -e "\nCTRL-C Pressed..."
  exit 1
}
trap clean_up EXIT
trap interrupt INT SIGINT
cat > "\$tempscript" << 'VIASHMAIN'
#!/bin/bash

set -eo pipefail

## VIASH START
# The following code has been auto-generated by Viash.
$( if [ ! -z ${VIASH_PAR_FASTQS+x} ]; then echo "${VIASH_PAR_FASTQS}" | sed "s#'#'\"'\"'#g;s#.*#par_fastqs='&'#" ; else echo "# par_fastqs="; fi )
$( if [ ! -z ${VIASH_PAR_SAMPLE_METADATA+x} ]; then echo "${VIASH_PAR_SAMPLE_METADATA}" | sed "s#'#'\"'\"'#g;s#.*#par_sample_metadata='&'#" ; else echo "# par_sample_metadata="; fi )
$( if [ ! -z ${VIASH_PAR_SAMPLE_FASTQ+x} ]; then echo "${VIASH_PAR_SAMPLE_FASTQ}" | sed "s#'#'\"'\"'#g;s#.*#par_sample_fastq='&'#" ; else echo "# par_sample_fastq="; fi )
$( if [ ! -z ${VIASH_PAR_METRICS+x} ]; then echo "${VIASH_PAR_METRICS}" | sed "s#'#'\"'\"'#g;s#.*#par_metrics='&'#" ; else echo "# par_metrics="; fi )
$( if [ ! -z ${VIASH_PAR_MOST_FREQUENT_UNMATCHED+x} ]; then echo "${VIASH_PAR_MOST_FREQUENT_UNMATCHED}" | sed "s#'#'\"'\"'#g;s#.*#par_most_frequent_unmatched='&'#" ; else echo "# par_most_frequent_unmatched="; fi )
$( if [ ! -z ${VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS+x} ]; then echo "${VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS}" | sed "s#'#'\"'\"'#g;s#.*#par_sample_barcode_hop_metrics='&'#" ; else echo "# par_sample_barcode_hop_metrics="; fi )
$( if [ ! -z ${VIASH_PAR_PER_PROJECT_METRICS+x} ]; then echo "${VIASH_PAR_PER_PROJECT_METRICS}" | sed "s#'#'\"'\"'#g;s#.*#par_per_project_metrics='&'#" ; else echo "# par_per_project_metrics="; fi )
$( if [ ! -z ${VIASH_PAR_PER_SAMPLE_METRICS+x} ]; then echo "${VIASH_PAR_PER_SAMPLE_METRICS}" | sed "s#'#'\"'\"'#g;s#.*#par_per_sample_metrics='&'#" ; else echo "# par_per_sample_metrics="; fi )
$( if [ ! -z ${VIASH_PAR_READ_STRUCTURES+x} ]; then echo "${VIASH_PAR_READ_STRUCTURES}" | sed "s#'#'\"'\"'#g;s#.*#par_read_structures='&'#" ; else echo "# par_read_structures="; fi )
$( if [ ! -z ${VIASH_PAR_ALLOWED_MISMATCHES+x} ]; then echo "${VIASH_PAR_ALLOWED_MISMATCHES}" | sed "s#'#'\"'\"'#g;s#.*#par_allowed_mismatches='&'#" ; else echo "# par_allowed_mismatches="; fi )
$( if [ ! -z ${VIASH_PAR_MIN_DELTA+x} ]; then echo "${VIASH_PAR_MIN_DELTA}" | sed "s#'#'\"'\"'#g;s#.*#par_min_delta='&'#" ; else echo "# par_min_delta="; fi )
$( if [ ! -z ${VIASH_PAR_FREE_NS+x} ]; then echo "${VIASH_PAR_FREE_NS}" | sed "s#'#'\"'\"'#g;s#.*#par_free_ns='&'#" ; else echo "# par_free_ns="; fi )
$( if [ ! -z ${VIASH_PAR_MAX_NO_CALLS+x} ]; then echo "${VIASH_PAR_MAX_NO_CALLS}" | sed "s#'#'\"'\"'#g;s#.*#par_max_no_calls='&'#" ; else echo "# par_max_no_calls="; fi )
$( if [ ! -z ${VIASH_PAR_QUALITY_MASK_THRESHOLD+x} ]; then echo "${VIASH_PAR_QUALITY_MASK_THRESHOLD}" | sed "s#'#'\"'\"'#g;s#.*#par_quality_mask_threshold='&'#" ; else echo "# par_quality_mask_threshold="; fi )
$( if [ ! -z ${VIASH_PAR_FILTER_CONTROL_READS+x} ]; then echo "${VIASH_PAR_FILTER_CONTROL_READS}" | sed "s#'#'\"'\"'#g;s#.*#par_filter_control_reads='&'#" ; else echo "# par_filter_control_reads="; fi )
$( if [ ! -z ${VIASH_PAR_FILTER_FAILING_QUALITY+x} ]; then echo "${VIASH_PAR_FILTER_FAILING_QUALITY}" | sed "s#'#'\"'\"'#g;s#.*#par_filter_failing_quality='&'#" ; else echo "# par_filter_failing_quality="; fi )
$( if [ ! -z ${VIASH_PAR_OUTPUT_TYPES+x} ]; then echo "${VIASH_PAR_OUTPUT_TYPES}" | sed "s#'#'\"'\"'#g;s#.*#par_output_types='&'#" ; else echo "# par_output_types="; fi )
$( if [ ! -z ${VIASH_PAR_UNDETERMINED_SAMPLE_NAME+x} ]; then echo "${VIASH_PAR_UNDETERMINED_SAMPLE_NAME}" | sed "s#'#'\"'\"'#g;s#.*#par_undetermined_sample_name='&'#" ; else echo "# par_undetermined_sample_name="; fi )
$( if [ ! -z ${VIASH_PAR_MOST_UNMATCHED_TO_OUTPUT+x} ]; then echo "${VIASH_PAR_MOST_UNMATCHED_TO_OUTPUT}" | sed "s#'#'\"'\"'#g;s#.*#par_most_unmatched_to_output='&'#" ; else echo "# par_most_unmatched_to_output="; fi )
$( if [ ! -z ${VIASH_PAR_OVERRIDE_MATCHER+x} ]; then echo "${VIASH_PAR_OVERRIDE_MATCHER}" | sed "s#'#'\"'\"'#g;s#.*#par_override_matcher='&'#" ; else echo "# par_override_matcher="; fi )
$( if [ ! -z ${VIASH_PAR_SKIP_READ_NAME_CHECK+x} ]; then echo "${VIASH_PAR_SKIP_READ_NAME_CHECK}" | sed "s#'#'\"'\"'#g;s#.*#par_skip_read_name_check='&'#" ; else echo "# par_skip_read_name_check="; fi )
$( if [ ! -z ${VIASH_PAR_SAMPLE_BARCODE_IN_FASTQ_HEADER+x} ]; then echo "${VIASH_PAR_SAMPLE_BARCODE_IN_FASTQ_HEADER}" | sed "s#'#'\"'\"'#g;s#.*#par_sample_barcode_in_fastq_header='&'#" ; else echo "# par_sample_barcode_in_fastq_header="; fi )
$( if [ ! -z ${VIASH_PAR_METRIC_PREFIX+x} ]; then echo "${VIASH_PAR_METRIC_PREFIX}" | sed "s#'#'\"'\"'#g;s#.*#par_metric_prefix='&'#" ; else echo "# par_metric_prefix="; fi )
$( if [ ! -z ${VIASH_PAR_LANE+x} ]; then echo "${VIASH_PAR_LANE}" | sed "s#'#'\"'\"'#g;s#.*#par_lane='&'#" ; else echo "# par_lane="; fi )
$( if [ ! -z ${VIASH_META_NAME+x} ]; then echo "${VIASH_META_NAME}" | sed "s#'#'\"'\"'#g;s#.*#meta_name='&'#" ; else echo "# meta_name="; fi )
$( if [ ! -z ${VIASH_META_FUNCTIONALITY_NAME+x} ]; then echo "${VIASH_META_FUNCTIONALITY_NAME}" | sed "s#'#'\"'\"'#g;s#.*#meta_functionality_name='&'#" ; else echo "# meta_functionality_name="; fi )
$( if [ ! -z ${VIASH_META_RESOURCES_DIR+x} ]; then echo "${VIASH_META_RESOURCES_DIR}" | sed "s#'#'\"'\"'#g;s#.*#meta_resources_dir='&'#" ; else echo "# meta_resources_dir="; fi )
$( if [ ! -z ${VIASH_META_EXECUTABLE+x} ]; then echo "${VIASH_META_EXECUTABLE}" | sed "s#'#'\"'\"'#g;s#.*#meta_executable='&'#" ; else echo "# meta_executable="; fi )
$( if [ ! -z ${VIASH_META_CONFIG+x} ]; then echo "${VIASH_META_CONFIG}" | sed "s#'#'\"'\"'#g;s#.*#meta_config='&'#" ; else echo "# meta_config="; fi )
$( if [ ! -z ${VIASH_META_TEMP_DIR+x} ]; then echo "${VIASH_META_TEMP_DIR}" | sed "s#'#'\"'\"'#g;s#.*#meta_temp_dir='&'#" ; else echo "# meta_temp_dir="; fi )
$( if [ ! -z ${VIASH_META_CPUS+x} ]; then echo "${VIASH_META_CPUS}" | sed "s#'#'\"'\"'#g;s#.*#meta_cpus='&'#" ; else echo "# meta_cpus="; fi )
$( if [ ! -z ${VIASH_META_MEMORY_B+x} ]; then echo "${VIASH_META_MEMORY_B}" | sed "s#'#'\"'\"'#g;s#.*#meta_memory_b='&'#" ; else echo "# meta_memory_b="; fi )
$( if [ ! -z ${VIASH_META_MEMORY_KB+x} ]; then echo "${VIASH_META_MEMORY_KB}" | sed "s#'#'\"'\"'#g;s#.*#meta_memory_kb='&'#" ; else echo "# meta_memory_kb="; fi )
$( if [ ! -z ${VIASH_META_MEMORY_MB+x} ]; then echo "${VIASH_META_MEMORY_MB}" | sed "s#'#'\"'\"'#g;s#.*#meta_memory_mb='&'#" ; else echo "# meta_memory_mb="; fi )
$( if [ ! -z ${VIASH_META_MEMORY_GB+x} ]; then echo "${VIASH_META_MEMORY_GB}" | sed "s#'#'\"'\"'#g;s#.*#meta_memory_gb='&'#" ; else echo "# meta_memory_gb="; fi )
$( if [ ! -z ${VIASH_META_MEMORY_TB+x} ]; then echo "${VIASH_META_MEMORY_TB}" | sed "s#'#'\"'\"'#g;s#.*#meta_memory_tb='&'#" ; else echo "# meta_memory_tb="; fi )
$( if [ ! -z ${VIASH_META_MEMORY_PB+x} ]; then echo "${VIASH_META_MEMORY_PB}" | sed "s#'#'\"'\"'#g;s#.*#meta_memory_pb='&'#" ; else echo "# meta_memory_pb="; fi )
$( if [ ! -z ${VIASH_META_MEMORY_KIB+x} ]; then echo "${VIASH_META_MEMORY_KIB}" | sed "s#'#'\"'\"'#g;s#.*#meta_memory_kib='&'#" ; else echo "# meta_memory_kib="; fi )
$( if [ ! -z ${VIASH_META_MEMORY_MIB+x} ]; then echo "${VIASH_META_MEMORY_MIB}" | sed "s#'#'\"'\"'#g;s#.*#meta_memory_mib='&'#" ; else echo "# meta_memory_mib="; fi )
$( if [ ! -z ${VIASH_META_MEMORY_GIB+x} ]; then echo "${VIASH_META_MEMORY_GIB}" | sed "s#'#'\"'\"'#g;s#.*#meta_memory_gib='&'#" ; else echo "# meta_memory_gib="; fi )
$( if [ ! -z ${VIASH_META_MEMORY_TIB+x} ]; then echo "${VIASH_META_MEMORY_TIB}" | sed "s#'#'\"'\"'#g;s#.*#meta_memory_tib='&'#" ; else echo "# meta_memory_tib="; fi )
$( if [ ! -z ${VIASH_META_MEMORY_PIB+x} ]; then echo "${VIASH_META_MEMORY_PIB}" | sed "s#'#'\"'\"'#g;s#.*#meta_memory_pib='&'#" ; else echo "# meta_memory_pib="; fi )

## VIASH END

unset_if_false=(
    par_filter_control_reads
    par_filter_failing_quality
    par_skip_read_name_check
    par_sample_barcode_in_fastq_header
)

for par in \${unset_if_false[@]}; do
    test_val="\${!par}"
    [[ "\$test_val" == "false" ]] && unset \$par
done

# Create arrays for inputs that contain multiple arguments
IFS=";" read -ra fastqs <<< "\$par_fastqs"
IFS=";" read -ra read_structures <<< "\$par_read_structures"
IFS=";" read -ra lane <<< "\$par_lane"
IFS=";" read -ra quality_mask_threashold <<< "\$par_quality_mask_threshold"
IFS=";" read -ra output_types <<< "\$par_output_types"

echo "> Creating temporary directory"
# create temporary directory and clean up on exit
TMPDIR=\$(mktemp -d "\$meta_temp_dir/\$meta_name-XXXXXX")
function clean_up {
 [[ -d "\$TMPDIR" ]] && rm -rf "\$TMPDIR"
}
trap clean_up EXIT
echo "> Temporary directory '\$TMPDIR' created"

if [ "\$par_most_unmatched_to_output" -eq "0" ] && [ ! -z "\$par_most_frequent_unmatched" ]; then
    echo "Requested to output 'most_frequent_unmatched' file, but 'most_unmatched_to_output' is set to 0."
    exit 1
fi

# The sgdemux documentation recommends the following settings:
#    1/3 of available threads for compression
#    1/6 of available threads for writing
#    1/6-1/3 of available threads for demultiplexing
declare -A thread_settings=(["compression_threads"]="3"
                            ["writing_threads"]="6"
                            ["demultiplexing_threads"]="3"
                           )
if [ ! -z "\$meta_cpus" ]; then
    for setting_var in "\${!thread_settings[@]}"; do
        denominator=\${thread_settings[\$setting_var]}
        result=\$(( \$meta_cpus / \$denominator ))
        if (( \$result == 0 )); then
            result=1
        fi
        declare \$setting_var=\$result
    done
fi

args=(
    --fastqs \${fastqs[@]}
    --sample-metadata "\$par_sample_metadata"
    --output-dir "\$TMPDIR"
    \${demultiplexing_threads:+--demux-threads \$demultiplexing_threads}
    \${writing_threads:+--writer-threads \$writing_threads}
    \${compression_threads:+--compressor-threads \$compression_threads}
    \${par_allowed_mismatches:+--allowed-mismatches \$par_allowed_mismatches}
    \${par_min_delta:+--min-delta \$par_min_delta}
    \${par_free_ns:+--free-ns \$par_free_ns}
    \${par_max_no_calls:+--max-no-calls \$par_max_no_calls}
    \${quality_mask_threashold:+--quality-mask-threshold "\${quality_mask_threashold[*]}" }
    \${output_types:+--output-types "\${output_types[*]}"}
    \${par_undetermined_sample_name:+--undetermined-sample-name \${par_undetermined_sample_name}}
    \${par_most_unmatched_to_output:+--par-most-unmatched-to-output \${par_most_unmatched_to_output}}
    \${par_override_matcher:+--override-matcher \$par_override_matcher}
    \${par_metric_prefix:+--metric-prefix \$par_metric_prefix}
    \${lane:+--lane "\${lane[*]}"}
    \${read_structures:+--read-structures \${read_structures[*]}}
    \${par_filter_control_reads:+--filter-control-reads}
    \${par_filter_failing_quality:+--filter-failing-quality}
    \${par_skip_read_name_check:+--skip-read-name-check}
    \${par_sample_barcode_in_fastq_header:+--sample-barcode-in-fastq-header}
)

echo "> Running sgdemux with arguments: \${args[@]}"
sgdemux \${args[@]}
echo "> Done running sgdemux"

echo "> Copying FASTQ files to \$par_sample_fastq"
find "\$TMPDIR" -type f -name "*.fastq.gz" -exec mv '{}' "\$par_sample_fastq" \\;

declare -A output_files=(["metrics.tsv"]="par_metrics"
                         ["most_frequent_unmatched.tsv"]="par_most_frequent_unmatched"
                         ["sample_barcode_hop_metrics.tsv"]="par_sample_barcode_hop_metrics"
                         ["per_project_metrics.tsv"]="par_per_project_metrics"
                         ["per_sample_metrics.tsv"]="par_per_sample_metrics"
                        )

for output_file_name in "\${!output_files[@]}"; do
    output_arg_variable_name=\${output_files[\$output_file_name]}
    destination="\${!output_arg_variable_name}"
    if [ ! -z "\$destination" ]; then
        echo "> Copying \$output_file file to \$destination"
        output_file="\$TMPDIR/\$output_file_name"
        if [ ! -f "\$output_file" ]; then
            echo "Expected a '\$output_file_name' to have been created! Exiting..."
            exit 1
        fi
        cp "\$output_file" "\$destination"
    fi
done

echo "> Finished!"
VIASHMAIN
bash "\$tempscript" &
wait "\$!"

VIASHEOF


if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then
  # strip viash automount from file paths
  
  if [ ! -z "$VIASH_PAR_FASTQS" ]; then
    unset VIASH_TEST_FASTQS
    IFS=';'
    for var in $VIASH_PAR_FASTQS; do
      unset IFS
      if [ -z "$VIASH_TEST_FASTQS" ]; then
      VIASH_TEST_FASTQS="$(ViashDockerStripAutomount "$var")"
    else
      VIASH_TEST_FASTQS="$VIASH_TEST_FASTQS;""$(ViashDockerStripAutomount "$var")"
    fi
    done
    VIASH_PAR_FASTQS="$VIASH_TEST_FASTQS"
  fi
  if [ ! -z "$VIASH_PAR_SAMPLE_METADATA" ]; then
    VIASH_PAR_SAMPLE_METADATA=$(ViashDockerStripAutomount "$VIASH_PAR_SAMPLE_METADATA")
  fi
  if [ ! -z "$VIASH_PAR_SAMPLE_FASTQ" ]; then
    VIASH_PAR_SAMPLE_FASTQ=$(ViashDockerStripAutomount "$VIASH_PAR_SAMPLE_FASTQ")
  fi
  if [ ! -z "$VIASH_PAR_METRICS" ]; then
    VIASH_PAR_METRICS=$(ViashDockerStripAutomount "$VIASH_PAR_METRICS")
  fi
  if [ ! -z "$VIASH_PAR_MOST_FREQUENT_UNMATCHED" ]; then
    VIASH_PAR_MOST_FREQUENT_UNMATCHED=$(ViashDockerStripAutomount "$VIASH_PAR_MOST_FREQUENT_UNMATCHED")
  fi
  if [ ! -z "$VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS" ]; then
    VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS=$(ViashDockerStripAutomount "$VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS")
  fi
  if [ ! -z "$VIASH_PAR_PER_PROJECT_METRICS" ]; then
    VIASH_PAR_PER_PROJECT_METRICS=$(ViashDockerStripAutomount "$VIASH_PAR_PER_PROJECT_METRICS")
  fi
  if [ ! -z "$VIASH_PAR_PER_SAMPLE_METRICS" ]; then
    VIASH_PAR_PER_SAMPLE_METRICS=$(ViashDockerStripAutomount "$VIASH_PAR_PER_SAMPLE_METRICS")
  fi
  if [ ! -z "$VIASH_META_RESOURCES_DIR" ]; then
    VIASH_META_RESOURCES_DIR=$(ViashDockerStripAutomount "$VIASH_META_RESOURCES_DIR")
  fi
  if [ ! -z "$VIASH_META_EXECUTABLE" ]; then
    VIASH_META_EXECUTABLE=$(ViashDockerStripAutomount "$VIASH_META_EXECUTABLE")
  fi
  if [ ! -z "$VIASH_META_CONFIG" ]; then
    VIASH_META_CONFIG=$(ViashDockerStripAutomount "$VIASH_META_CONFIG")
  fi
  if [ ! -z "$VIASH_META_TEMP_DIR" ]; then
    VIASH_META_TEMP_DIR=$(ViashDockerStripAutomount "$VIASH_META_TEMP_DIR")
  fi
fi


# check whether required files exist
if [ ! -z "$VIASH_PAR_SAMPLE_FASTQ" ] && [ ! -e "$VIASH_PAR_SAMPLE_FASTQ" ]; then
  ViashError "Output file '$VIASH_PAR_SAMPLE_FASTQ' does not exist."
  exit 1
fi
if [ ! -z "$VIASH_PAR_METRICS" ] && [ ! -e "$VIASH_PAR_METRICS" ]; then
  ViashError "Output file '$VIASH_PAR_METRICS' does not exist."
  exit 1
fi
if [ ! -z "$VIASH_PAR_MOST_FREQUENT_UNMATCHED" ] && [ ! -e "$VIASH_PAR_MOST_FREQUENT_UNMATCHED" ]; then
  ViashError "Output file '$VIASH_PAR_MOST_FREQUENT_UNMATCHED' does not exist."
  exit 1
fi
if [ ! -z "$VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS" ] && [ ! -e "$VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS" ]; then
  ViashError "Output file '$VIASH_PAR_SAMPLE_BARCODE_HOP_METRICS' does not exist."
  exit 1
fi
if [ ! -z "$VIASH_PAR_PER_PROJECT_METRICS" ] && [ ! -e "$VIASH_PAR_PER_PROJECT_METRICS" ]; then
  ViashError "Output file '$VIASH_PAR_PER_PROJECT_METRICS' does not exist."
  exit 1
fi
if [ ! -z "$VIASH_PAR_PER_SAMPLE_METRICS" ] && [ ! -e "$VIASH_PAR_PER_SAMPLE_METRICS" ]; then
  ViashError "Output file '$VIASH_PAR_PER_SAMPLE_METRICS' does not exist."
  exit 1
fi


exit 0
