#!/usr/bin/python -tt
#
# appliance-creator: Create a virtual appliance partitioned disk image
#
# 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 sys
import shutil
import optparse
import appcreate
import imgcreate
import logging


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

def parse_options(args):
    parser = optparse.OptionParser()
    
    appopt = optparse.OptionGroup(parser, "Appliance options",
                                  "These options define the created Appliance.")
    appopt.add_option("-c", "--config", type="string", dest="kscfg",
                      help="Path to kickstart config file")
    appopt.add_option("-n", "--name", type="string", dest="name",
                      help="Appliance name")
    appopt.add_option("-f", "--format", type="string", dest="format", default="raw",
                      help="Disk format (raw, qcow2, ...)")
    appopt.add_option("-p", "--package", type="string", dest="package", default="none",
                      help="Package format (zip, none, ....)")
    appopt.add_option("", "--vmem", type="int", dest="vmem", default=512,
                      help="amount of virtual memory for appliance in MB (default: 512)")
    appopt.add_option("", "--vcpu", type="int", dest="vcpu", default=1,
                      help="number of virtual cpus for appliance (default: 1)")
    parser.add_option_group(appopt)
    
    # 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)

    imgcreate.setup_logging(parser)
    
    (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.package != "zip" and options.package != "none":# and not options.package == "tg.bz2" and not options.package == "none":
        raise Usage("bad option %s, Currently only zip is supported" % options.package)

          
    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 appliance-creator as root"
        return 1

    try:
        ks = imgcreate.read_kickstart(options.kscfg)
    except imgcreate.CreatorError, e:
        logging.error("Unable to load kickstart file '%s' : %s" % (options.kscfg, e))
        return 1

    name = imgcreate.build_name(options.kscfg)
    if options.name:
        name = options.name
 
    creator = appcreate.ApplianceImageCreator(ks, name, options.format, options.package, options.vmem, options.vcpu)
    creator.tmpdir = options.tmpdir
    
    try:
        creator.mount("NONE", options.cachedir)
        creator.install()
        creator.configure()
        creator.unmount()
        creator.package()    
    except imgcreate.CreatorError, e:
        logging.error("Unable to create appliance : %s" % e)
        return 1
    finally:
        creator.cleanup()

    return 0

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



