#!/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.

set -x
set +e

main() {

    echo "getting files"
    dx download "$genome" -o - | gunzip > genome.fa
    dx download "$meIndex" -o - | tar zxvf -
    read_fn=`dx describe "$trimmed_reads" --name | cut -d'.' -f1`
    dx download "$trimmed_reads" -o - | gunzip > "$read_fn".fq

    mv genome.fa input

    echo `ls input`
    mkdir output
    bismark -n 1 -l 28 -output_dir output --temp_dir output input "$read_fn".fq

    # 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.

    echo `ls /home/dnanexus/output`
    outfile="$read_fn".mapped_methylseq.tgz
    tar zcvf $outfile output
    mapped_files=$(dx upload /home/dnanexus/$outfile --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.

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