#!/usr/bin/env python

# see http://stackoverflow.com/questions/4109436/processing-multiple-values-for-one-single-option-using-getopt-optparse

import os, sys
from optparse import OptionParser
from optparse import Option, OptionValueError
import tarfile
import subprocess

VERSION = '0.11.5'

class MultipleOption(Option):
    ACTIONS = Option.ACTIONS + ("extend",)
    STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
    TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
    ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)

    def take_action(self, action, dest, opt, value, values, parser):
        if action == "extend":
            values.ensure_value(dest, []).append(value)
        else:
            Option.take_action(self, action, dest, opt, value, values, parser)


def main():
    PROG = os.path.basename(os.path.splitext(__file__)[0])
    long_commands = ('fastq')
    short_commands = {'f':'fastq'}
    description = """Runs Fastqc"""
    parser = OptionParser(option_class=MultipleOption,
                          usage='usage: %prog [OPTIONS] COMMAND [BLOG_FILE]',
                          version='%s %s' % (PROG, VERSION),
                          description=description)
    parser.add_option('-f', '--fastq',
                      action="extend", type="string",
                      dest='fastq',
                      metavar='FASTQ',
                      help='Fastq file')
    parser.add_option('-t', '--tar',
                      action="extend", type="string",
                      dest='tar',
                      metavar='TAR',
                      help='Tar file')

    if len(sys.argv) == 1:
        parser.parse_args(['--help'])

    OPTIONS, args = parser.parse_args()
    #print "arguments:", args
    print "options:", OPTIONS

    fastq_files = OPTIONS.fastq
    if fastq_files == None:
      fastq_files = []

    tar_files = OPTIONS.tar
    if tar_files == None:
      tar_files = []

    for tar_file in tar_files:
      # untar
      tar = tarfile.open(tar_file)
      tar.list()
      tar_file_contents = tar.getnames()
      tar.extractall()
      tar.close()
      # add to fastq
      fastq_files = fastq_files + tar_file_contents
      print fastq_files

    bashCommand = "fastqc --outdir . "+" ".join(fastq_files)
    print "CMD: "+bashCommand
    process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
    output, error = process.communicate()
    bashCommand = "tar zcf fastqc_reports.tar.gz *.html *.zip"
    print "CMD: "+bashCommand
    process = subprocess.Popen(['/bin/bash', '-c', bashCommand], stdout=subprocess.PIPE)
    output, error = process.communicate()

if __name__ == '__main__':
    main()
