#!/usr/bin/python
#coding:utf-8
import os, sys
import yum, pickle
import tempfile
usages = \
"""
Usage: sunyums [OPTION]... [FILE]...
    Output and match all dependent installation packages

Example:
 sunyums packname1 packname2
 sunyums packname1 packname2 --config=file --comps=comps.xml
 sunyums packname1 packname2 --mandatory=1 --default=1 --options=0

Options:
    --config=file.conf  supply an yum config file,  default: optional
    --comps=comps.xml   supply an parsed comps.xml  default: optional
    --mandatory=True    include mandatory packages  default: True
    --default=True      include mandatory packages  default: True
    --options=False     include mandatory packages  default: False
"""
class Application(object):

    def __init__(self, args):
        self.args       = args[1:]
        self.yums       = yum.YumBase()
        self.comps      = None
        self.config     = None
        self.groups     = []
        self.mandatory  = True
        self.default    = True
        self.options    = False

        self.basePacks  = []
        self.origPacks  = []
        self.packages   = []

    def str2bool(self, s):
        """Converts an on/off, yes/no, true/false string to 1/0."""
        if s and s.upper() in [ 'ON', 'YES', 'Y', 'TRUE', '1', 'ENABLED', 'ENABLE']:
            return True
        else:
            return False

    def usages(self):
        print usages
        sys.exit(0)

    def parseArgs(self):

        if not self.args: 
            self.usages()

        for arg in self.args:
            if arg in [ '-h', '--help']:
                self.usages()

            elif arg.startswith('--comps='):
                self.comps = arg.split('=')[1]
                
            elif arg.startswith('--config='):
                self.config = arg.split('=')[1]

            elif arg.startswith('--mandatory='):
                self.mandatory = self.str2bool(arg.split('=')[1])

            elif arg.startswith('--default='):
                self.default = self.str2bool(arg.split('=')[1])

            elif arg.startswith('--options='):
                self.options = self.str2bool(arg.split('=')[1])

            else:
                self.groups.append(arg)

    def depends(self):
        pkgs = []
        avail = self.yums.pkgSack.returnNewestByNameArch()
        for p in avail:
            if p.name in self.basePacks:
                pkgs.append(p)

        done = 0
        while not done:
            done = 1
            results = self.yums.findDeps(pkgs)
            for pkg in results.keys():
                for req in results[pkg].keys():
                    reqlist = results[pkg][req]
                    for r in reqlist:
                        if r.name not in self.basePacks:
                            self.basePacks.append(r.name)
                            pkgs.append(r)
                            done = 0

    def allgroups(self):
        for grp in self.yums.comps.groups:
            self.packages.extend(grp.packages)

    def handerPackages(self, name):
        if not self.packages:
            self.allgroups()

        if name in self.packages and \
                    name not in self.basePacks:
            self.basePacks.append(name)

        if name not in self.origPacks:
            self.origPacks.append(name)

    def handerGroups(self, name):
        groups = []
        if not self.yums.comps.has_group(name):
            return
            
        valid_groups = self.yums.comps.return_group(name.encode('utf-8'))
        if self.mandatory:
            groups.extend(valid_groups.mandatory_packages.keys())
        if self.default:
            groups.extend(valid_groups.default_packages.keys())
        if self.options:
            groups.extend(valid_groups.options_packages.keys())

        for package in groups:
            self.handerPackages(package)

    def handerEnviron(self, name):
        groups = []
        if not self.yums.comps.has_environment(name):
            return

        valid_environ = self.yums.comps.return_environment(name)
        for grp in valid_environ.groups:
            self.handerGroups(grp)

    def run(self):

        if self.comps and os.path.exists(self.comps):
            self.yums.comps.add(self.comps)

        if self.config and os.path.exists(self.config):
            self.yums.doConfigSetup(fn=self.config, init_plugins=False)

        self.yums.conf.cache = 0
        for rpm in self.groups:
            if rpm[0] == '@':
                self.handerGroups(rpm[1:])

            elif rpm[0] == '^':
                self.handerEnviron(rpm[1:])

            else:
                self.handerPackages(rpm)

        self.depends()

        for o in self.origPacks:
            if o not in self.basePacks:
                print '#%s' % o

        for p in self.basePacks:
            print p

if __name__ == "__main__":
    app = Application(sys.argv)
    app.parseArgs()
    app.allgroups()
    app.run()









