task AppendToStringArray {
    Array[String] array
    String string

    command {
        echo "${sep='\n' array}
        ${string}"
    }

    output {
        Array[String] outArray = read_lines(stdout())
    }

    runtime {
        memory: 1
    }
}

# This task will fail if the MD5sum doesn't match the file.
task CheckFileMD5 {
    File file
    String MD5sum

    command {
        set -e -o pipefail
        MD5SUM=$(md5sum ${file} | cut -d ' ' -f 1)
        [ $MD5SUM = ${MD5sum} ]
    }
}

task ConcatenateTextFiles {
    Array[File] fileList
    String combinedFilePath
    Boolean? unzip = false
    Boolean? zip = false

    command {
        set -e -o pipefail
        ${"mkdir -p $(dirname " + combinedFilePath + ")"}
        ${true='zcat' false= 'cat' unzip} ${sep=' ' fileList} \
        ${true="| gzip -c" false="" zip} > ${combinedFilePath}
    }

    output {
        File combinedFile = combinedFilePath
    }

    runtime {
        memory: 1
    }
}

task CreateLink {
    # Making this of type File will create a link to the copy of the file in the execution
    # folder, instead of the actual file.
    String inputFile
    String outputPath

    command {
        ln -sf ${inputFile} ${outputPath}
    }

    output {
        File link = outputPath
    }
}

# inspired by https://gatkforums.broadinstitute.org/wdl/discussion/9616/is-there-a-way-to-flatten-arrays
task FlattenStringArray {
    Array[Array[String]] arrayList

    command {
        for line in $(echo ${sep=', ' arrayList}) ; \
        do echo $line | tr -d '"[],' ; done
    }

    output {
        Array[String] flattenedArray = read_lines(stdout())
    }

    runtime {
        memory: 1
    }
}

task MapMd5 {
    Map[String,String] map

    command {
        cat ${write_map(map)} | md5sum - | sed -e 's/  -//'
    }

    output {
        String md5sum = read_string(stdout())
    }

    runtime {
        memory: 1
    }
}


task ObjectMd5 {
    Object the_object

    command {
        cat ${write_object(the_object)} |  md5sum - | sed -e 's/  -//'
    }

    output {
        String md5sum = read_string(stdout())
    }

    runtime {
        memory: 1
    }
}

task StringArrayMd5 {
    Array[String] stringArray

    command {
        set -eu -o pipefail
        echo ${sep=',' stringArray} | md5sum - | sed -e 's/  -//'
    }

    output {
        String md5sum = read_string(stdout())
    }

    runtime {
        memory: 1
    }
}