#!/usr/bin/env python

__author__  = 'Gouichi Iisaka <iisaka51@hotmail.com>'
__date__ = 'Sun 12 May 2007'
__version__ = '3.0'

import os
import sys
sys.path.insert(0,'/usr/local/lib/python')
import string
import scatter.cmd

class App(scatter.cmd.Application):
    def __init__(self,argv=sys.argv):
        import getpass
        self.user = getpass.getuser()
        self.usage_msg = "Usage: %prog [options] PATTERN user"
        self.default_option = [
	    scatter.cmd.Option("-e","--execcmd",action="store_const",
		    dest="execcmd",
		    default='/usr/local/bin/trsh',
		    help="Command name for execution. default is ssh"),
	    scatter.cmd.Option("-R","--regex",action="store",
		    dest="pattern",
		    help="Use PATTERN as regular expression"),
	    scatter.cmd.Option("-s","--signal",action="store",
		    dest="signal",
                    default='TERM',
		    help="Specify send signal"),
	    scatter.cmd.Option("","--kill",action="store_true",
		    dest="kill",
                    default=False,
		    help="Set the username for remote host"),
	    ]

        scatter.cmd.Application.__init__(self,argv)

        if sys.platform == 'linux2':
            self.ps_option="-efaw"
            self.user_position=0
        else:
            self.ps_option="-efa"
            self.user_position=1

    def __delete__(self):
        if not self.options.do_debug:
            self.batch.close()

    def usageHeader(self):
        if self.prog == 'GenKillCmd':
	    self.usage_title = "GenKillCmd -- " + \
                  "Generate script to kill the process of the remote host."
        else:
	    self.usage_title = "GatherPS -- " + \
                  "Gathering proces infomations from the remote host."
        sys.stderr.write(
            "%s\n"
	    "Version: %s \n"
	    "Copyright (C) 2002-2007 %s\n\n"
	    % ( self.usage_title, __version__, __author__)
        )

    def gather_ps(self):
        self.batch = scatter.shell.ScatterRun(self.options.execcmd, self.user )
        self.batch.setColorMode(0)
        self.batch.setPrintmode(0,1)

        self.batch.buildScript(self.nodes.nodes, "ps " + self.ps_option )
        self.batch.writeOut()
        self.batch.doScript()

    def parse_ps(self):
        os.chdir( self.batch.getWorkDir())
        if self.options.pattern != None:
            grepcmd = 'egrep -e "%s" o.*' % self.args[0]
        else:
            grepcmd = 'egrep "%s" o.*' % self.args[0]
        pipe = os.popen(grepcmd)
        procs = pipe.readlines()

	if self.options.do_debug:
            print self.batch.getWorkDir()
            print grepcmd

        trans = string.maketrans(';',' ')
        for line in procs:
            line = string.translate(line,trans)
            buf = string.splitfields(line)
            p = string.find(buf[0], ':')
            if p < 0:
                remotehost = pipe.readline()
                remotehost = remotehost[0:-1]
                self.user = buf[self.user_position]
		outposition = 0
            else:
                remotehost = buf[0][2:p]
                self.user = buf[self.user_position][p+1:]
		outposition = 2

            if self.options.kill:
                output = '%s %s -l %s "kill -%s %s" \t# %s' % (
                        self.execcmd, remotehost, self.user,
                        self.options.signal,
			buf[1], string.join(buf[7:]) )
            else:
                output = '%s' % ( line[outposition:-1] )
            if self.user == self.args[1] or self.args[1] == '*':
                print output

    def run(self):
        self.gather_ps()
        self.parse_ps()


if __name__ == '__main__':
    app = App()
    app.run()
