#!/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
    flavor = ""
    osdir = "os"
    sourcedir = "source"
    debugdir = "debug"
    isodir = "iso"
    cdsize = "685.0"
    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 "default" not in config.sections():
        print ("Check that the file %s exists and that it has a 'default' section" % opts.config)
        sys.exit(1)

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

    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', 'cdsize'):
        config.set('default', 'cdsize', cdsize)

    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', 'manifest'))

    if not opts.destdir == "*CONFFILE*":
        config.set('default', 'destdir', opts.destdir)

    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':
        if opts.do_all or opts.do_gather:
            mygather = pypungi.gather.Gather(config, pkglist)
            mygather.getPackageObjects()
            mygather.downloadPackages()
            if config.getboolean('default', 'getsource'):
                mygather.getSRPMList()
                mygather.downloadSRPMs()

        mypungi = pypungi.pungi.Pungi(config)

        if opts.do_all or opts.do_buildinstall:
           mypungi.doBuildinstall()
           mypungi.doGetRelnotes()

        if opts.do_all or opts.do_packageorder:
           mypungi.doPackageorder()

        if opts.do_all or opts.do_splittree:
             mypungi.doSplittree()

        if opts.do_all or opts.do_createiso:
           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'),
                                      config.get('default', 'flavor'),
                                      'source', 'SRPM')
        if opts.do_all or opts.do_splittree:
            mypungi.doSplitSRPMs()

        if opts.do_all or opts.do_createiso:
            mypungi.doCreateIsos()

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

    def get_arguments():
        parser = OptionParser(version="%prog 0.3.7")
        parser.add_option("--destdir", default="*CONFFILE*", dest="destdir",
          help='destination directory (defaults to current directory)')
        parser.add_option("-c", "--conf", default='/etc/pungi/pungi.conf', dest="config",
          help='Config file to use')
        parser.add_option("--all-stages", action="store_true", default=True, dest="do_all",
          help="Enable ALL stages")
        parser.add_option("-G", action="store_true", default=False, dest="do_gather",
          help="Flag to enable processing the Gather stage")
        parser.add_option("-B", action="store_true", default=False, dest="do_buildinstall",
          help="Flag to enable processing the BuildInstall stage")
        parser.add_option("-P", action="store_true", default=False, dest="do_packageorder",
          help="Flag to enable processing the Package Order stage")
        parser.add_option("-S", action="store_true", default=False, dest="do_splittree",
          help="Flag to enable processing the SplitTree stage")
        parser.add_option("-I", action="store_true", default=False, dest="do_createiso",
          help="Flag to enable processing the CreateISO stage")


        (opts, args) = parser.parse_args()
        if opts.do_gather or opts.do_buildinstall or opts.do_packageorder or opts.do_splittree or opts.do_createiso:
            opts.do_all = False
        if len(sys.argv) < 2:
            parser.print_help()
            sys.exit(0)
        return (opts, args)

    def get_packagelist(manifest):
    # Get the list of packages from the manifest file
        try:
            manifestfile = open(manifest, 'r')

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

        pkglist = manifestfile.readlines()
        manifestfile.close()
        return pkglist

    main()
