#!/usr/bin/python -tt
#
# livecd-creator : Creates Live CD based for Fedora.
#
# Copyright 2007, Red Hat  Inc.
#
# 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 os.path
import sys
import time
import optparse

import imgcreate

class Usage(Exception):
    def __init__(self, msg = None, no_error = False):
        Exception.__init__(self, msg, no_error)

def parse_options(args):
    parser = optparse.OptionParser()

    imgopt = optparse.OptionGroup(parser, "Image options",
                                  "These options define the created image.")
    imgopt.add_option("-c", "--config", type="string", dest="kscfg",
                      help="Path to kickstart config file")
    imgopt.add_option("-b", "--base-on", type="string", dest="base_on",
                      help="Add packages to an existing live CD iso9660 image.")
    imgopt.add_option("-f", "--fslabel", type="string", dest="fs_label",
                      help="File system label (default based on config name)")
    parser.add_option_group(imgopt)

    # options related to the config of your system
    sysopt = optparse.OptionGroup(parser, "System directory options",
                                  "These options define directories used on your system for creating the live image")
    sysopt.add_option("-t", "--tmpdir", type="string",
                      dest="tmpdir", default="/var/tmp",
                      help="Temporary directory to use (default: /var/tmp)")
    sysopt.add_option("", "--cache", type="string",
                      dest="cachedir", default=None,
                      help="Cache directory to use (default: private cache")
    parser.add_option_group(sysopt)

    # debug options not recommended for "production" images
    # Start a shell in the chroot for post-configuration.
    parser.add_option("-l", "--shell", action="store_true", dest="give_shell",
                      help=optparse.SUPPRESS_HELP)
    # Don't compress the image.
    parser.add_option("-s", "--skip-compression", action="store_true", dest="skip_compression",
                      help=optparse.SUPPRESS_HELP)
    parser.add_option("", "--skip-minimize", action="store_true", dest="skip_minimize",
                      help=optparse.SUPPRESS_HELP)

    (options, args) = parser.parse_args()
    if not options.kscfg or not os.path.isfile(options.kscfg):
        raise Usage("Kickstart config '%s' does not exist" %(options.kscfg,))
    if options.base_on and not os.path.isfile(options.base_on):
        raise Usage("Live CD ISO '%s' does not exist" %(options.base_on,))
    if options.fs_label and len(options.fs_label) > imgcreate.FSLABEL_MAXLEN:
        raise Usage("CD labels are limited to 32 characters")

    return options

def main():
    try:
        options = parse_options(sys.argv[1:])
    except Usage, (msg, no_error):
        if no_error:
            out = sys.stdout
            ret = 0
        else:
            out = sys.stderr
            ret = 2
        if msg:
            print >> out, msg
        return ret

    if os.geteuid () != 0:
        print >> sys.stderr, "You must run livecd-creator as root"
        return 1

    if options.fs_label:
        fs_label = options.fs_label
        name = fs_label
    else:
        name = imgcreate.build_name(options.kscfg, "livecd-")

        fs_label = imgcreate.build_name(options.kscfg,
                                        "livecd-",
                                        maxlen = imgcreate.FSLABEL_MAXLEN)

        print "Using label '%s' and name '%s'" % (fs_label, name)

    ks = imgcreate.read_kickstart(options.kscfg)

    creator = imgcreate.LiveImageCreator(ks, name, fs_label)
    creator.tmpdir = options.tmpdir
    creator.skip_compression = options.skip_compression
    creator.skip_minimize = options.skip_minimize

    try:
        creator.mount(options.base_on, options.cachedir)
        creator.install()
        creator.configure()
        if options.give_shell:
            print "Launching shell. Exit to continue."
            print "----------------------------------"
            creator.launch_shell()
        creator.unmount()
        creator.package()
    except imgcreate.CreatorError, e:
        print >> sys.stderr, "Error creating Live CD : %s" % e
        return 1
    finally:
        creator.cleanup()

    return 0

if __name__ == "__main__":
    sys.exit(main())
