#!/usr/bin/env python

import sys,os,commands

# some gunk to make George happy.
if os.getenv('SRT_DIST') != None:
    base = os.getenv('SRT_PRIVATE_CONTEXT')
    if base == '.':
        base = os.getenv('SRT_PUBLIC_CONTEXT')
    if base == None:
        print 'Your SRT environment is crap'
        sys.exit(1)
    path=base+"/PerfTools/python"
    sys.path.append(base+"/PerfTools/python")
        

try:
    import perftool.CallGraphCanvas as CGC
except ImportError,err:
    print "ImportError: \"%s\"\nDid you set your PYTHONPATH?"%err
    sys.exit(1)
import perftool.ProfLogger as PL
import getopt



class PTRun:
    def __init__(self,argv):

        try:
            (opts,rest) = getopt.getopt(argv[1:],"c:l:b:n:p:g")
        except getopt.GetoptError:
            self.usage()

        if len(opts) == 0: self.usage()

        options = {}
        for (flag,arg) in opts: options[flag] = arg

        pl = None
        if "-c" in options.keys():
            cmd = options["-c"]
            try:
                log = options["-l"]
            except KeyError:
                log = "/dev/null"

            pl = PL.ProfLogger()
            (prof_libs,prof_out) = pl.run(cmd,log)

        if "-n" in options.keys():
            pid = options["-n"]
            print "got -n",pid

            try:
                pid = int(pid)
            except ValueError:
                pid = self.guess_pid()
                
            try:
                base = options["-b"]
            except KeyError:
                base = "default"

            if not pl: pl = PL.ProfLogger()

            pl.postproc("prof_libs.out.%d"%pid,"prof.out.%d"%pid,base)
        
        cutoff = 0
        if "-p" in options.keys():
            try:
                cutoff = int(options["-p"])
            except ValueError:
                pass

        if "-g" in options.keys():
                
            try:
                base = options["-b"]
            except KeyError:
                base = "default"
            
            print "Setting initial path cutoff to",cutoff
            CGC.spawn(base,cutoff)

    def guess_pid(self):
        print "guessing pid"
        ls = commands.getoutput("ls -t prof.out.*  | head -1 | cut -f 3 -d .")
        pid = ls.strip()
        print "using",pid
        return int(pid)

    def usage(self):
        print """
usage: ptrun.py [options]

There are three steps to running:
        
Three steps:

1) Run program under the proifiler to get prof.out.PID and
prof_libs.out.PID files

2) Postprocess these files to get BASE_{names,fullnames,paths,edges}
files.

3) Use BASE_{...} files to generate call graphs and explore these
graphs to find potential spots for improvement.

These steps can be run with separate invocations of ptrun.py or all at
once depending on what options are given.

To run step 1 include:

        -c <"program to run plus args">
        -l <logfile>

Example: ptrun.py -c "prog -f flag inputfile" -l prog.out

To run step 2 include:

        -n <PID or "guess" to use most recent>
        -b <basename for post process files>

Example: ptrun.py -n guess -b basename

To run step 3 include:

        -g
        -b <basename for post process files>
        -p <optional initial path_cut>

Example: ptrun.py -g -b basename -p 100

"""
        sys.exit(1)
        

if __name__ == '__main__':
    PTRun(sys.argv)
    
