#!/bin/bash -x
# Bismark-ENCODE-WGBS 0.0.1
# Generated by dx-app-wizard.
#
# Basic execution pattern: Your app will run on a single machine from
# beginning to end.
#
# Your job's input variables (if any) will be loaded as environment
# variables before this script runs.  Any array inputs will be loaded
# as bash arrays.
#
# Any code outside of main() (or any entry point you may add) is
# ALWAYS executed, followed by running the entry point itself.
#
# See https://wiki.dnanexus.com/Developer-Portal for tutorials on how
# to modify this file.

main() {

    echo "Value of genomes: '$genomes'"

    # The following line(s) use the dx command-line tool to download your file
    # inputs to the local file system using variable names for the filenames. To
    # recover the original filenames, you can use the output of "dx describe
    # "$variable" --name".

    genome_name=""
    for i in ${!genomes[@]}
    do
        filename=`dx describe "${genomes[$i]}" --name`
        dx download "${genomes[$i]}" -o - | gunzip > "$filename".fa
        genome_name="${genome_name}${filename}"
    done
    echo "genomes  downloaded"
    cat *.fa > genome.fa

    mkdir input
    mv genome.fa input
    echo "Prep Genome"
    bismark_genome_preparation --path_to_bowtie /usr/bin/ input
    echo "Genome Prepped"

    # Fill in your application code here.
    #
    # To report any recognized errors in the correct format in
    # $HOME/job_error.json and exit this script, you can use the
    # dx-jobutil-report-error utility as follows:
    #
    #   dx-jobutil-report-error "My error message"
    #
    # Note however that this entire bash script is executed with -e
    # when running in the cloud, so any line which returns a nonzero
    # exit code will prematurely exit the script; if no error was
    # reported in the job_error.json file, then the failure reason
    # will be AppInternalError with a generic error message.

    # The following line(s) use the dx command-line tool to upload your file
    # outputs after you have created them on the local file system.  It assumes
    # that you have used the output field name for the filename for each output,
    # but you can change that behavior to suit your needs.  Run "dx upload -h"
    # to see more options to set metadata.
    outname=input/"$genome_name".bisulfite.tgz
    tar zcvf "$outname" input/Bisulfite_Genome/
    meIndex=$(dx upload "$outname" --brief)

    # The following line(s) use the utility dx-jobutil-add-output to format and
    # add output variables to your job's output as appropriate for the output
    # class.  Run "dx-jobutil-add-output -h" for more information on what it
    # does.
    #echo "Adding output -- files should be renamed"

    dx-jobutil-add-output meIndex "$meIndex" --class=file
}
