#!/usr/bin/python
import os, sys, time
import Bcfg2.Logger, Bcfg2.Server.Core, Bcfg2.Options
import Bcfg2.Server.Plugins.Metadata, Bcfg2.Server.Plugin

class searchCore(Bcfg2.Server.Core.Core):
    # On définit une classe parce qu'il faut mettre quelque chose au-dessus
    # de la classe Core si on veut récupérer les informations ...
    # C'est nul.

    def __init__(self, repo, plgs, struct, gens, passwd, svn,
                 encoding):
        try:
            Bcfg2.Server.Core.Core.__init__(self, repo, plgs, struct, gens, 
                                                passwd, svn, encoding)
        except Bcfg2.Server.Core.CoreInitError, msg:
            print "Core load failed because %s" % msg
            raise SystemExit(1)
        i = 0
        while self.fam.Service() or i < 5:
            i += 1
        
    def do_search(self, searchgroup):
        """Search for clients belonging to a group"""
        clients = []
        clist = self.metadata.clients.keys()
        clist.sort()
        for client in clist:
            profile = self.metadata.clients[client]
            gdata = [grp for grp in self.metadata.groups[profile][1]]
            if searchgroup in gdata:
                clients.append(client)
        return clients

if __name__ == '__main__':
    # Bon ça ce sont les trucs recopiés de bcfg2-info
    optinfo = {
            'configfile': Bcfg2.Options.CFILE, 
            'help': Bcfg2.Options.HELP,
              }
    optinfo.update({'repo': Bcfg2.Options.SERVER_REPOSITORY,
                    'svn': Bcfg2.Options.SERVER_SVN,
                    'plugins': Bcfg2.Options.SERVER_PLUGINS,
                    'structures': Bcfg2.Options.SERVER_STRUCTURES,
                    'generators': Bcfg2.Options.SERVER_GENERATORS,
                    'password': Bcfg2.Options.SERVER_PASSWORD,
                    'event debug': Bcfg2.Options.DEBUG,
                    'encoding': Bcfg2.Options.ENCODING})
    setup = Bcfg2.Options.OptionParser(optinfo)
    setup.parse([])
    loop = searchCore(setup['repo'], setup['plugins'], setup['structures'],
                        setup['generators'], setup['password'], '',
                        setup['encoding'])
    # On cherche les clients
    clients = loop.do_search('backup-client')
    # On génère un truc qui va bien pour ces clients
    
