#!/usr/bin/python -tt
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# 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 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.

import os
import pypungi.gather
import pypungi.pungi
import yum

from ConfigParser import SafeConfigParser

def main():
    # Set some default variables, can be overrided in config file

    # Turn this into a dict someday, to iterate over when setting defaults
    osdir = "os"
    sourcedir = "source"
    debugdir = "debug"
    isodir = "iso"
    relnotefilere = "eula.txt fedora.css GPL README-BURNING-ISOS-en_US.txt RELEASE-NOTES-en_US.html ^RPM-GPG"
    relnotedirre = "images stylesheet-images"
    relnotepkgs = "fedora-release fedora-release-notes"
    
    (opts, args) = get_arguments()

    config = SafeConfigParser()
    config.read(opts.config)

    if not config.has_option('default', 'osdir'):
        config.set('default', 'osdir', osdir)

    if not config.has_option('default', 'sourcedir'):
        config.set('default', 'sourcedir', sourcedir)

    if not config.has_option('default', 'debugdir'):
        config.set('default', 'debugdir', debugdir)

    if not config.has_option('default', 'isodir'):
        config.set('default', 'isodir', isodir)

    if not config.has_option('default', 'relnotefilere'):
        config.set('default', 'relnotefilere', relnotefilere)

    if not config.has_option('default', 'relnotedirre'):
        config.set('default', 'relnotedirre', relnotedirre)

    if not config.has_option('default', 'relnotepkgs'):
        config.set('default', 'relnotepkgs', relnotepkgs)

    # set some other defaults
    if not config.has_option('default', 'product_path'):
        config.set('default', 'product_path', config.get('default', 'product_name'))

    if not config.has_option('default', 'iso_basename'):
        config.set('default', 'iso_basename', config.get('default', 'product_name'))

    pkglist = get_packagelist(config.get('default', 'comps'))

    destdir = config.get('default', 'destdir')

    if not os.path.exists(destdir):
        try:
            os.makedirs(destdir)
        except OSError, e:
            print >> sys.stderr, "Error: Cannot create destination dir %s" % destdir
            sys.exit(1)

    cachedir = config.get('default', 'cachedir')

    if not os.path.exists(cachedir):
        try:
            os.makedirs(cachedir)
        except OSError, e:
            print >> sys.stderr, "Error: Cannot create cache dir %s" % cachedir
            sys.exit(1)

    # Actually do work.
    if not config.get('default', 'arch') == 'source':
        mygather = pypungi.gather.Gather(config, pkglist)
        mygather.getPackageObjects()
        mygather.downloadPackages()
        if config.getboolean('default', 'getsource'):
            mygather.getSRPMList()
            mygather.downloadSRPMs()

        mypungi = pypungi.pungi.Pungi(config)
        mypungi.doBuildinstall()
        mypungi.doPackageorder()
        mypungi.doGetRelnotes()
        mypungi.doSplittree()
        mypungi.doCreateSplitrepo()
        mypungi.doCreateIsos()

    # Do things slightly different for src.
    if config.get('default', 'arch') == 'source':
        # we already have all the content gathered
        mypungi = pypungi.pungi.Pungi(config)
        mypungi.topdir = os.path.join(config.get('default', 'destdir'),
                                      config.get('default', 'version'),
                                      'source', 'SRPM')
        mypungi.doSplitSRPMs()
        mypungi.doCreateIsos()

if __name__ == '__main__':
    from optparse import OptionParser
    import sys

    def get_arguments():
    # hack job for now, I'm sure this could be better for our uses
        usage = "usage: %s [options]" % sys.argv[0]
        parser = OptionParser(usage=usage)
       # parser.add_option("--destdir", default=".", dest="destdir",
       #   help='destination directory (defaults to current directory)')
       # parser.add_option("--cachedir", default="./cache", dest="cachedir",
       #   help='cache directory (defaults to cache subdir of current directory)')
       # parser.add_option("--comps", default="comps.xml", dest="comps",
       #   help='comps file to use')
       # parser.add_option("--yumconf", default="yum.conf", dest="yumconf",
       #   help='yum config file to use')
       # parser.add_option("--arch", default="i386", dest="arch",
       #   help='Base arch to use')
       # parser.add_option("--version", default="test", dest="version",
       #   help='Version of the spin')
       # parser.add_option("--discs", default=5, type="int", dest="discs",
       #   help='Number of discs to spin')
       # parser.add_option("-q", "--quiet", default=False, action="store_true",
       #   help="Output as little as possible")
        parser.add_option("-c", "--conf", default='/etc/pungi/pungi.conf', dest="config",
          help='Config file to use')



        (opts, args) = parser.parse_args()
        #if len(opts) < 1:
        #    parser.print_help()
        #    sys.exit(0)
        return (opts, args)

    def get_packagelist(myComps):
    # Get the list of packages from the comps file
        try:
            compsobj = yum.comps.Comps()
            compsobj.add(myComps)

        except IOError:
            print >> sys.stderr, "pungi: No such file:\'%s\'" % opts.comps
            sys.exit(1)

        pkglist = []
        for group in compsobj.groups:
            pkglist += group.packages
        return pkglist

    main()
