#!/bin/env python
'''
    A 'Hello World' qube jobytype

    It will accept a string in the front-end while building the job, and echo that string back at
    runtime on the remote worker.

'''
#======================================
#  $Revision: #1 $
#  $Change: 9976 $
#======================================
#

import sys
import os
import time
import socket

try:
    import qb
except:
    if 'QBDIR' in os.environ:
        QBDIR = os.environ['QBDIR']
    else:
        if os.name == 'posix':
            if os.uname()[0] == 'Darwin':
                QBDIR = '/Applications/pfx/qube'
            else:
                QBDIR = '/usr/local/pfx/qube'

    sys.path.append('%s/api/python' % QBDIR)
    import qb
        

def main(buildAgendaJob):
    import sys
    # optionally point to a test supervisor
    #qb.setsupervisor('YourTestSupervisor')

    
    job = {
        'package':{'dev': ''}   # set dev to anything other than a null string to pretty-print the job and work dicts in the back end
    }

    job['prototype'] = 'helloWorld'
    job['name'] = 'a Hello World test job'

    # here's the data we actually want to send to the worker to echo back to us
    job['package']['testString'] = 'At hostname %s the time at the tone is %s' % (socket.gethostname(), time.strftime('%c', time.localtime()) )

    if buildAgendaJob:
        
        job['cpus'] = 5

        # you can build agendas 2 ways: with a qb.gen* function, or by hand for more control.  You
        # can even construct a basic agenda with the genframes, and then iterate over the resulting
        # list of dictionaires to customize them further.

        #job['agenda'] = qb.genframes('1-5')

        # this is equivalent to genframes('1-5')
        agenda = []
        for i in range(1,6):
            work = {'name': str(i)}
            agenda.append(work)
        job['agenda'] = agenda

    if '--arch' in sys.argv:
        arcSize = qb.archivejob('job.qja', job, format=qb.QB_API_BINARY)
        print 'job.qja: %s bytes' % arcSize
    else:
        submitted = qb.submit(job)[0]
        print 'job id: %(id)s' % submitted

    sys.exit()


if __name__ == '__main__':
    # set buildAgendaJob to True to build and submit an agenda-based job, False to build a job
    # similar to Qube's cmdline job (non-agenda based)

    buildAgendaJob = False
    main(buildAgendaJob)

    sys.exit() 
