#!/usr/bin/python
#
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Library General Public License as published by
# the Free Software Foundation; version 2 only
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# Copyright 2004, 2005 Red Hat, Inc.
#
# Author: Phil Knirsch
#

import sys, getopt, os.path

PYRPMDIR = "/usr/share/pyrpm"
if not PYRPMDIR in sys.path:
    sys.path.append(PYRPMDIR)
from pyrpm import __version__
from pyrpm import *
from pyrpm.yum import *
from pyrpm.database.memorydb import *

def usage():
    print """
    Yum install and remove interative test of all packages in the repositories
    pyrpmcheckinstall [options] [numcpu=VAL] [logfile=VAL] [DIRS... | PACKAGES...]

options:
    [-?, --help] [--version]
    [--quiet] [-v, --verbose] [-q] [-y] 
    [-c CONFIGFILE] [--dbpath DIRECTORY]
    [-r, --root DIRECTORY, --installroot DIRECTORY]
    [-h, --hash] [--force] [--oldpackage] [--justdb] [--test]
    [--ignoresize] [--ignorearch] [--exactarch]
    [--noconflicts] [--fileconflicts]
    [--nodeps] [--signature]
    [--noorder] [--noscripts] [--notriggers]
    [--autoerase] [--installpkgs="pkg1 pkg2 pkg2 ..."]
    [--enablerepo repoid|repoglob] [--disablerepo repoid|repoglob]
    [--exclude pkgname/pkgglob]
    [--nocache] [--cachedir DIRECTORY]
    [--obsoletes] [--noplugins]

DIRS:     Directories with packages for possible installation
PACKAGES: Same for rpm binary packages
"""

#
# Function to loop over a pkglist to test
#
def testPkglist(yum, numcpu, j):
    yum.setCommand("update")
    if yum.prepareTransaction() == 0:
        return 0
    pkglist = yum.repos.getPkgs()
    plen = len(pkglist)
    pkglist = pkglist[j*plen/numcpu:(j+1)*plen/numcpu]
    i = j*plen/numcpu
    for pkg in pkglist:
        i += 1
        #if pkg["name"] != "bash":
        #   continue
        yum.setCommand("update")
        if yum.prepareTransaction() == 0:
            break
        resolver = yum.opresolver
        log.info1("Updating package [%d/%d]: %s/%s\n" % (i, plen, pkg.getNEVRA(), pkg["sourcerpm"]))
        resolver.update(pkg)
        if not yum.runDepRes():
            continue
        if yum.runCommand() == 0:
            break

        yum.setCommand("remove")
        if yum.prepareTransaction() == 0:
            break
        resolver = yum.opresolver
        for rpkg in resolver.getDatabase().getPkgs()[:]:
            resolver.erase(rpkg)
        if not yum.runDepRes():
            continue
        if yum.runCommand() == 0:
            break


#
# Main program
#
def main():
    # Our yum worker object
    yum = RpmYum(rpmconfig)

    # Disabled fileconflicts per default in yum
    rpmconfig.nofileconflicts = 1

    # Default is to be a little verbose.
    rpmconfig.verbose = 1

    # Default number of cpus we're running on
    numcpu = 1

    # Default logfile. Output to stdout if None
    logfile = None

    # Argument parsing
    args = parseYumOptions(sys.argv[1:], yum)

    if args:
        if args[0].startswith("numcpu="):
            numcpu = int(args[0][7:])
            args = args[1:]
        if args[0].startswith("logfile="):
            logfile = args[0][8:]
            args = args[1:]

    # Read additional dirs/packages
    pkglist = []
    if args:
        for fname in args:
            if os.path.isdir(fname):
                readDir(fname, pkglist, rtags=rpmconfig.resolvertags)
            elif fname.endswith(".rpm"):
                pkg = package.RpmPackage(rpmconfig, fname)
                try:
                    pkg.read(tags=rpmconfig.resolvertags)
                    pkg.close()
                except (IOError, ValueError), e:
                    log.error("%s: %s", pkg, e)
                    continue
                pkglist.append(pkg)

    # Create fake repository
    memory_repo = database.repodb.RpmRepoDB(rpmconfig, [], rpmconfig.buildroot, "pyrpmcheckinstall-memory-repo")
    for pkg in pkglist:
        memory_repo.addPkg(pkg)
    yum.repos.addDB(memory_repo)

    mainbr = rpmconfig.buildroot[:]
    for j in xrange(numcpu):
        if numcpu != 1:
            rpmconfig.buildroot = mainbr+"."+str(j)
        pid = os.fork()
        if pid == 0:
            if logfile != None:
                fname = logfile[:]
                if numcpu != 1:
                    fname += "."+str(j)
                log.setInfoLogging("*", FileLog(fname))
                log.setDebugLogging("*", FileLog(fname))
            testPkglist(yum, numcpu, j)
            return 1
    os.waitpid(-1, 0)
    return 1

if __name__ == '__main__':
    if not run_main(main):
        sys.exit(1)

# vim:ts=4:sw=4:showmatch:expandtab
