#! /usr/bin/env python

#############################################################
#                                                           #
#   Author: Nicolas Joly , Bertrand Neron                   #
#   Organization:'Biological Software and Databases' Group, #
#                Institut Pasteur, Paris.                   #
#   Distributed under GPLv2 Licence. Please refer to the    #
#   COPYING.LIB document.                                   #
#                                                           #
#############################################################

import os, sys, time

MOBYLEHOME = None
if os.environ.has_key('MOBYLEHOME'):
  MOBYLEHOME = os.environ['MOBYLEHOME']
if not MOBYLEHOME:
  sys.exit('MOBYLEHOME must be defined in your environment')

sys.path.append(os.path.join(MOBYLEHOME,'Src'))

from Mobyle.ConfigManager import Config
from Mobyle.MobyleLogger import MLogger
MLogger()

from Mobyle.Admin import Admin 
from Mobyle.Utils import getStatus as utils_getStatus

cfg = Config()
adm = cfg.admindir()
lst = os.listdir(adm)

for job in lst:
    fil = os.path.join(adm, job)
    if not os.path.isfile(fil) or job[0] == '.': 
        continue
    admin = Admin(fil)
    
    print "%s" % ("-"*80)
    
    jid = admin.getJobID()
    if jid == None:
        print "Unknown job %s" % job
        continue
    key = jid.split(os.path.sep)[-1]
    exc_alias = admin.getExecutionAlias()
    que = admin.getQueue()
    try:
        sta = utils_getStatus(jid)
    except Exception , err:
        print >> sys.stderr , "ERROR : %s : getStatus : %s "%( jid , err )
        continue
    print "%s -- %s/%s -- %s" % (key, exc_alias , que, sta)
    
    nam = admin.getJobName()
    ema = admin.getEmail()
    tim = time.strftime("%x %X", admin.getDate())
    ses = admin.getSession()
    adr = admin.getRemote()
    wfid = admin.getWorkflowID()
    if wfid :
        src = 'LOCAL'
        wf_nam = '/'.join( wfid.split('/')[-2:] )
    elif ses :
        wf_nam = 'STANDALONE'
        src = 'LOCAL'
    else :
        wf_nam = 'UNKNOWN'
        src =  'REMOTE'
        
    print "%s -- %s -- %s -- %s -- %s -- %s " % (nam, ema, tim, src, wf_nam , adr)
    fil = os.path.join(cfg.results_path(), nam, key, '.command')
    try:
        fh = open(fil)
        cmd = fh.readline().strip()
    except IOError, err:
        cmd = "no command line"
    finally:
        try:
            fh.close()
        except:
            pass
    print "%s" % cmd

sys.exit(0)
