import sys
import glob
import threading
import signal
from subprocess import call

from config.settings import *
from settings import *

from util.log import log

def run_pgbadger():

    e = { }
    for k, v in os.environ.iteritems(): e[k] = v
    
    filelist = glob.glob(LOGS_PATH + '/*.csv.gz')

    if not filelist:
        filelist = glob.glob(LOGS_PATH + '/*.csv')
        if not filelist:
            log('No log files found')
            return
        
    pgbadger_stdout = open(PGBADGER_REPORT_PATH, 'w')
    pgbadger_stderr = open(PGBADGER_ERROR_PATH, 'w')
    
    pgbadger_options = [ PGBADGER_PATH,
        '-x', 'html',
        '-o', '-',
        ]
    
    try:
        pgbadger_options.extend(PGBADGER_OPTIONS)
    except NameError:
        pass
    
    pgbadger_options.extend(sorted(filelist))
    
    log('Starting pgbadger.')
    
    pgbadger = call(pgbadger_options, 
        stdout=pgbadger_stdout, stderr=pgbadger_stderr,
        env = e,
        preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL)
        )
        
    # If you are wondering about the preexec_fn parameter above, see:
    #   http://blog.nelhage.com/2010/02/a-very-subtle-bug/
    
    pgbadger_stdout.close()
    pgbadger_stderr.close()

    log('pgbadger done.')
    


def start_pgbadger():

    class BadgerWorker(threading.Thread):
        
        def run(self):
            run_pgbadger()
    
    th = BadgerWorker()
    th.start()
    
    return th