#!python
"""
Retrieve the UWS status of a given job.

The UWS system is used by VOSpace for asynchronous actions. Normally users do not use or need to use this script.
checkJobPhase is provide for admin usage.

This script is used to retrieve the state of a job using X509 authentication.

"""


import sys
import vos
import optparse
import os
import logging

if __name__ == '__main__':

    usage = """ Get the status of a UWS job. Syntax: 
               
                 checkJobPhase --cert=<certfile> <JOBURL>/phase """

    parser=optparse.OptionParser(usage)

    parser.add_option("--certfile",help="location of your CADC security certificate file",default=os.path.join(os.getenv("HOME","."),".ssl/cadcproxy.pem"))
    parser.add_option("-v","--verbose",action="store_true",help="print some diagnostics")
    parser.add_option("-d","--debug",action="store_true",help="print all diagnositics")


    (opt,args)=parser.parse_args()


    if opt.verbose:
        log_level = logging.INFO
    elif opt.debug:
        log_level = logging.DEBUG
    else:
        log_level = logging.ERROR

    logging.getLogger('vos').setLevel(log_level)
    logging.getLogger('vos').addHandler(logging.StreamHandler())

    if len(args) !=  1:
        parser.error("You must specifiy a job url")
        sys.exit(-1)

    try:
        client = vos.Client(certFile=opt.certfile)
        sys.stdout.write("%s\n" % client.getJobStatus(args[0]))
    except KeyboardInterrupt:
        sys.stderr.write("Received keyboard interrupt. Execution aborted...\n")
        sys.exit(-1)
    except Exception as e:
        sys.stderr.write(str(e))
        sys.exit(-1)
    sys.exit(0)
