#!/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, os.path, random

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

def usage():
    print """
    Yum install and remove interative test
    pyrpmrandomizer [options] number of iterations [DIRS... | PACKAGES...]

options:
    [-?, --help] [--version]
    [--quiet] [-v, --verbose] [-y]
    [-c CONFIGFILE] [--dbpath DIRECTORY] [-r, --root DIRECTORY]
    [-h, --hash] [--force] [--oldpackage] [--justdb] [--test]
    [--ignoresize] [--ignorearch] [--exactarch]
    [--noconflicts] [--fileconflicts]
    [--nodeps] [--signature]
    [--noorder] [--noscripts] [--notriggers]
    [--autoerase] [--installpkgs="pkg1 pkg2 pkg2 ..."]

Number of iterations: How many install/erase operations should be run
DIRS:     Directories with packages for possible installation
PACKAGES: Same for rpm binary packages"""


class FakeRepo:
    """Fake repository class to stuff into our yum object for additional
    packages via dirs or files"""
    def __init__(self, pkglist):
        self.pkglist = pkglist

    def getPkgs(self):
        return self.pkglist

    def importFilelist(self):
        return 1

    def isFilelistImported(self):
        return 1

    def _matchesFile(self, fname):
        return 1

#
# 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

    # Argument parsing
    args = parseYumOptions(sys.argv[1:], yum)
    if not args:
        usage()
        return 0

    # Remember number of iterations
    count = int(args.pop(0))

    # Read additional dirs/packages
    pkglist = []
    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:
                rpmconfig.printError("%s: %s\n" % (pkg, e))
                continue
            pkglist.append(pkg)


    # Create fake repository
    frepo = pyrpm.database.memorydb.RpmMemoryDB(rpmconfig, None)
    frepo.addPkgs(pkglist)

    # Always use the same random sequence
    random.seed(12345)
    yum.setCommand("update")
    while count > 0:
        if not yum.repos_read and len(frepo.getPkgs()) > 0:
            yum.repos.addDB(frepo)
        if yum.prepareTransaction() == 0:
            break
        resolver = yum.opresolver
        count -= 1
        if count % 2:
            pkglist = yum.repos.getPkgs()
            pkg = pkglist[random.randrange(0, len(pkglist))]
            while pkg["name"].find("-debuginfo") >= 0:
                pkglist = yum.repos.getPkgs()
                pkg = pkglist[random.randrange(0, len(pkglist))]
            yum.setCommand("update")
            rpmconfig.printInfo(1, "Updating package %s\n" % pkg.getNEVRA())
            resolver.update(pkg)
        else:
            pkglist = resolver.getDatabase().getPkgs()
            pkg = pkglist[random.randrange(0, len(pkglist))]
            yum.setCommand("remove")
            rpmconfig.printInfo(1, "Erasing package %s\n" % pkg.getNEVRA())
            resolver.erase(pkg)
        if not yum.runDepRes():
            continue
        if yum.runCommand() == 0:
            break

    return 1

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

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