#!/usr/bin/env python

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

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

from ConfigParser import *

class myConfigParser(ConfigParser):
    def optionxform(self, optionstr):
        return optionstr

class App(scatter.cmd.Application):
    def __init__(self,argv=sys.argv):
        sys,argv.append('dummy')
        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.Application.__init__(self,argv)

        self.configfile = 'GatherSysInfo.conf'
        self.configs = myConfigParser()
        self.configs.read(os.path.join(self.nodes.searchdir, self.configfile))

        self.cmdoptions = {}
        if self.configs.has_section('options'):
            for o in self.configs.options('options'):
                self.cmdoptions[ o ] = self.configs.get('options',o)
            self.configs.remove_section('options')

    def usageHeader(self):
        sys.stderr.write(
            "%s -- Gathering informations from cluster system.\n"
            "Version: %s in Python\n" 
            "Copyright (C) 2003-2006 %s \n"
	    % ( self.prog, __version__,  __author__ )
        )

    def mktmpdir(self):
        import time
        curtime = time.localtime()
        self.workdirname = 'Gather.%d%02d%02d%02d%02d%02d' % (
                    curtime[0], curtime[1], curtime[2],
                    curtime[3], curtime[4], curtime[5] )
        self.workdir = os.path.join('/tmp', self.workdirname )
        os.mkdir(self.workdir)
        os.chdir(self.workdir)

    def pre_scatter(self, host):
        self.batch = scatter.shell.ScatterRun(self.options.execcmd)
        self.batch.setComment('---------------------------------')
        self.batch.setColorMode(1)   # monochrome
        self.batch.setPrintmode(0,0)

        self.nodes.set_ignore_nodes(self.options.ignore_nodes)
        if self.configs.has_section('ignore'):
            self.nodes.add_ignore_nodes(self.config.get('options', 'ignore'))

        if host == 'all':
            self.nodes.set_add_nodes('localhost')
            self.nodes.get_nodes(self.options.hostlist)
        else:
            self.nodes.get_nodes(host)

    def gather_sysinfo(self,host):
        outfiles = self.configs.options(host)
        outfiles.sort()
        for outfile in outfiles:
            if outfile[-6:] == 'stdout':
                sys.stdout.write(self.configs.get(host, outfile ) + '\n')
                continue
            if outfile[-6:] == 'stderr':
                sys.stderr.write(self.configs.get(host, outfile ) + '\n')
                continue

            (msg, cmd) = tuple(string.splitfields(self.configs.get(host, outfile),':'))
            sys.stdout.write( msg + '\n')
            self.batch.buildScript(self.nodes.nodes, cmd)
            self.batch.writeOut()
            self.batch.doScript(os.path.join(self.workdir, outfile))
            if self.options.do_debug:
                print cmd, outfile
            self.batch.initScript()

    def run(self):
        self.mktmpdir()

        if self.configs.has_section('all'):
            self.pre_scatter('all')
            self.gather_sysinfo('all')
            self.configs.remove_section('all')

        for host in self.configs.sections():
            self.pre_scatter(host)
            self.gather_sysinfo(host)
            self.configs.remove_section(host)


        sys.stdout.write('\nIf you have any questions,\n'
		     'Please send next file to support stuff.\n')
        cmd = 'cd /tmp && /bin/tar -zcf %s.tgz %s 2>/dev/null' % (
               self.workdirname, self.workdirname)
        os.system( cmd )
        cmd = 'cd /tmp && /bin/rm -rf %s ; /bin/ls /tmp/%s.tgz' % (
               self.workdirname, self.workdirname)
        os.system( cmd )


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