File: mic-image-creator

package info (click to toggle)
mic2 0.19-2
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 932 kB
  • ctags: 864
  • sloc: python: 9,292; sh: 1,347; makefile: 62
file content (799 lines) | stat: -rwxr-xr-x 36,043 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
#!/usr/bin/python -t
#
# mic-image-creator : Creates all kinds of image
#
# Copyright 2009, Intel 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 logging
import shutil
import subprocess
import string
import tempfile
import traceback
import re

import mic.appcreate as appcreate
import mic.imgcreate as imgcreate
import mic.chroot as mychroot

import signal
def sig_interrupt(signum=None, frame=None):
    raise imgcreate.CreatorError('Canceled by ^C.')
signal.signal(signal.SIGINT, sig_interrupt)

try:
    import mic.__version__
    version = mic.__version__.version
except:
    version = 'unknown'

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

    def __str__(self):
        return self.msg

class Debugger():
    def __init__(self):
       self.debug_level = 0
       self.tmpfd = tempfile.TemporaryFile()

    def set_debug_level(self, level = 1):
       self.debug_level = level

    def record_callstack(self):
       if self.debug_level == 0:
           return
       traceback.print_exc(file=self.tmpfd)

    def dump_debuginfo(self):
       if self.debug_level == 0:
           return
       COLOR_BLACK = "\033[00m"
       COLOR_RED =   "\033[1;31m"
       self.tmpfd.seek(0, 0)
       buf = self.tmpfd.read()
       self.tmpfd.close()
       print >> sys.stderr, "\n%s%s%s\n" % (COLOR_RED, buf, COLOR_BLACK)


debugger = Debugger()

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

    commonopt = optparse.OptionGroup(parser, "General options",
                                  "These options define the created image.")

    commonopt.add_option("-c", "--config", type="string", dest="config",
                    help="Path to kickstart config file")

    commonopt.add_option("-f", "--format", type="string", dest="format",
                    help="Image format, you can specify as fs, livecd, liveusb, loop, raw, nand, mrstnand, ubi, jffs2, vdi or vmdk")

    parser.add_option_group(commonopt)

    # 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",
                      help="Temporary directory to use (default: /var/tmp)")
    sysopt.add_option("-k", "--cache", type="string",
                      dest="cachedir", default=None,
                      help="Cache directory to use (default: private cache)")
    sysopt.add_option("-o", "--outdir", type="string",
                      dest="outdir", default=None,
                      help="Output directory to use (default: current work dir)")
    sysopt.add_option("", "--release", type="string",
                      dest="release", default=None,
                      help="Generate a release with all necessary files for publishing.")
    sysopt.add_option("", "--genchecksum", action="store_true",
                      dest="genchecksum", default=False,
                      help="Generate checksum for image file if this option is provided")
    sysopt.add_option("-P", "--prefix", type="string",
                      dest="prefix", default=None,
                      help="Image name prefix (default: meego)")
    sysopt.add_option("-S", "--suffix", type="string",
                      dest="suffix", default=None,
                      help="Image name suffix (default: date stamp)")
    sysopt.add_option("-b", "--build-bootstrap", action="store_true",
                      dest="buildbootstrap", default=False,
                      help="Build a bootstrap, it should be used with -B or --bootstrap together")
    sysopt.add_option("", "--mainrepo", type="string",
                      dest="mainrepo", default=None,
                      help="Specify main repo name, it must be a repo name in your kickstart file")
    sysopt.add_option("", "--siteconf", type="string", action="store",
                      dest="siteconf",
                      help="Specify site config file, it can be used to set tmpdir, cachedir, outputdir, it also can be used to remap/reroute a repo in kickstart to another equivalent repo, the default site configs are /etc/mic2/mic2.conf and ~/.mic2.conf.")
    sysopt.add_option("", "--ignore-siteconf", action="store_true",
                      dest="ignore_siteconf", default=False,
                      help="Ignore site configs, this will ignore the default site configs, also ignore --siteconf option.")
    sysopt.add_option("", "--repo", type="string", action="append", metavar="REPO",
                      dest="addrepos",
                      help="Specify additional repo, it may be a simple URL or a complicated tuple string, you can specify multiple repos using this option multiple times")
    sysopt.add_option("", "--default-ks", type="string",
                      help="Set which kickstart file from repos to select in advance, if specified, there isn't interaction needed any more.")
    sysopt.add_option("-B", "--bootstrap", type="string",
                      dest="bootstrap", default=None,
                      help="Use a given bootstrap env to create image")
    sysopt.add_option("-a", "--arch", type="string",
                      dest="arch", default=None,
                      help="Specify target arch of image, for example: arm")
    sysopt.add_option("", "--save-kernel", action="store_true",
                      dest="save_kernel", default=False,
                      help="Save kernel image file into outdir")
    sysopt.add_option("", "--use-comps", action="store_true",
                      dest="use_comps", default=False,
                      help="Use comps instead of patterns if comps exists")
    sysopt.add_option("", "--run-mode", type="int",
                      dest="run_mode", default=-1,
                      help="Specify run mode, 0 means legacy, 1 means bootstrap, by default it is gotten from config file.")
    sysopt.add_option("", "--alt-initrd-name", type="string",
                      dest="alt_initrd_name", default=None,
                      help="Name of alternate initrd image, if NOT to use the one from kernel package")
    sysopt.add_option("", "--record-pkgs", type="string",
                      dest="record_pkgs", default=None,
                      help="Record the installed packages, valid values: name, content")
    sysopt.add_option("", "--local-pkgs-path", type="string",
                      dest="local_pkgs_path", default=None,
                      help="Path for local pkgs (rpms) to be installed")
    parser.add_option_group(sysopt)

    # options related to live USB
    liveusbopt = optparse.OptionGroup(parser, "Live USB file image options",
                                  "These options are for creating the live USB file image")
    liveusbopt.add_option("-i", "--interactive", action="store_true",
                      dest="interactive", default=False,
                      help="Directly write into a USB disk.")
    liveusbopt.add_option("", "--fstype", type="string",
                      dest="fstype", default="vfat",
                      help="File system type for live USB file image, ext3 or vfat, the default is vfat.")
    liveusbopt.add_option("", "--overlay-size-mb", type="int", default=64,
                      help="Overlay size in MB as unit, it means how size changes you can save in your live USB disk.")
    parser.add_option_group(liveusbopt)

    # options related to nand image
    nandopt = optparse.OptionGroup(parser, "MRST NAND image options",
                                  "These options are for creating the MRST NAND image")
    nandopt.add_option("", "--initrd-url", type="string",
                      dest="initrd_url", default=None,
                      help="URL of initrd.img, if it need to be retrieved from remote site.")
    nandopt.add_option("", "--initrd-path", type="string",
                      dest="initrd_path", default=None,
                      help="Path of initrd.img, if it was saved in local filesystem.")
    nandopt.add_option("", "--kernel-url", type="string",
                      dest="kernel_url", default=None,
                      help="URL of kernel file(vmlinuz), if it need to be retrieved from remote site.")
    nandopt.add_option("", "--kernel-path", type="string",
                      dest="kernel_path", default=None,
                      help="Path of kernel file(vmlinuz), if it was saved in local filesystem.")
    nandopt.add_option("", "--kernel-rpm-url", type="string",
                      dest="kernel_rpm_url", default=None,
                      help="URL of kernel rpm package, if it need to be retrieved from remote site.")
    nandopt.add_option("", "--kernel-rpm-path", type="string",
                      dest="kernel_rpm_path", default=None,
                      help="Path of kernel rpm package, if it was saved in local filesystem.")

    nandopt.add_option("", "--bootimg-only", action="store_true", dest="bootimg_only",
                      help="Create boot image only.")
    parser.add_option_group(nandopt)

    # Don't compress the image.
    sysopt.add_option("-s", "--skip-compression", action="store_true", dest="skip_compression",
                      default=False, help=optparse.SUPPRESS_HELP)
    parser.add_option("", "--skip-minimize", action="store_true", dest="skip_minimize",
                      default=False, help=optparse.SUPPRESS_HELP)
    sysopt.add_option("-p", "--package", type="string", dest="package", default="none",
                      help="Package format, this option will package up output into a given-format package, "
                           "currently only tar, tar.gz and tar.bz2 are supported, the default "
                           "is none, i.e. doesn't package up output")
    parser.add_option("", "--traceback", action="store_true",
                      default=False, help="Dump call stack")

    # Start a shell in the chroot for post-configuration.
    parser.add_option("", "--image-info", type="string",
                      dest="image_info", default=None,
                      help=optparse.SUPPRESS_HELP)
    parser.add_option("", "--pipe", type="string",
                      dest="pipe", default=None,
                      help=optparse.SUPPRESS_HELP)
    parser.add_option("-l", "--shell", action="store_true", dest="give_shell",
                      help=optparse.SUPPRESS_HELP)

    imgcreate.setup_logging(parser)

    logging.getLogger().setLevel(logging.FATAL)
    (options, args) = parser.parse_args()
    if logging.getLogger().level in (logging.DEBUG, logging.INFO, logging.WARN) or options.traceback:
        debugger.set_debug_level(1)

    # kickstart file isn't necessary any more
    if options.config and not os.path.isfile(options.config):
        raise FatalError("kickstart config '%s' does'not exist" % options.config)

    if options.record_pkgs is not None and options.record_pkgs not in ('name', 'content'):
        raise FatalError("Please specify what to be recorded: \"name\", \"content\"")

    return options


def run_in_bootstrap(bootstrap, args, bindmounts, arch = None):
    def chroot_bootstrap():
        """Chroot into bootstrap env"""
        try:
            os.chroot(bootstrap)
            os.chdir("/")
        except:
           raise FatalError("Please specify a workable bootstrap env.")

    globalmounts = mychroot.setup_chrootenv(bootstrap, bindmounts)
    if arch and arch.startswith("arm"):
        imgcreate.setup_qemu_emulator(bootstrap, "arm")
    ret = subprocess.call(args, preexec_fn = chroot_bootstrap)
    mychroot.cleanup_chrootenv(bootstrap, bindmounts, globalmounts)

def get_siteconf_diropt(siteconf, option):
    if not siteconf:
        return None
    if option:
        if siteconf.has_section("main") and siteconf.has_option("main", option):
            value = siteconf.get("main", option)
            if value:
                try:
                    imgcreate.fs.makedirs(value)
                except:
                    raise FatalError("Error: invalid tmpdir name %s" % value)
                return os.path.abspath(os.path.expanduser(value))
    return None

def get_siteconf_opt(siteconf, section, option):
    if not siteconf:
        return None
    if option:
        if siteconf.has_section(section) and siteconf.has_option(section, option):
            value = siteconf.get(section, option)
            if value:
                return value
    return None

def rebuild_argv(argv, options):
    blacklist = ["bootstrap", "buildbootstrap", "mainrepo", "repo", "default_ks", "siteconf", "prefix", "ignore_siteconf", "package", "run_mode"]
    myargv = []
    myargv.append(argv[0])

    optlist = options.__dict__
    for key in optlist.keys():
        if optlist[key]:
            if key in blacklist:
                continue
            if key == "cachedir":
                myargv.append("--%s=%s" % ("cache", optlist[key]))
            elif optlist[key] == True:
                myargv.append("--%s" % key.replace("_", "-"))
            else:
                myargv.append("--%s=%s" % (key.replace("_", "-"), optlist[key]))

    if logging.getLogger().level in (logging.DEBUG, logging.INFO, logging.WARN):
        myargv.append("--traceback")

    return myargv

def main():
    options = parse_options(sys.argv[1:])

    if os.geteuid () != 0:
        raise FatalError("You must run mic-image-creator as root")

    if options.siteconf and not os.path.isfile(options.siteconf):
        raise FatalError("Error: site config %s doesn't exist" % options.siteconf)

    if not options.ignore_siteconf:
        siteconf = imgcreate.misc.read_siteconf(options.siteconf)
        imgcreate.misc.output_siteconf(siteconf)
    else:
        siteconf = None

    distro_name = get_siteconf_opt(siteconf, "main", "distro_name")
    if not distro_name:
        distro_name = "MeeGo"

    if imgcreate.is_meego_bootstrap("/") or (options.arch and options.arch.strip().startswith("arm")):
       """ Obviously don't need bootstrap for MeeGo and bootstrap """
       options.run_mode = 0
    elif options.run_mode  == -1:
        run_mode = get_siteconf_opt(siteconf, "main", "run_mode")
        if not run_mode:
            run_mode = "0"
        if run_mode not in ("0", "1"):
            raise FatalError("Error: invalid run mode %s" % run_mode)
        else:
            options.run_mode = int(run_mode)
    if options.run_mode not in (0, 1):
        raise FatalError("Error: invalid run mode %d" % options.run_mode)

    if options.run_mode == 1:
        if not options.buildbootstrap and not options.bootstrap:
            default_bootstrap_root = "/var/cache/meego-bootstrap"
            if not os.path.exists(default_bootstrap_root):
                os.makedirs(default_bootstrap_root)
            if imgcreate.is_meego_bootstrap(default_bootstrap_root):
                options.bootstrap = default_bootstrap_root
            else:
                if os.path.isdir(default_bootstrap_root):
                    ret = mychroot.cleanup_mounts(default_bootstrap_root)
                    if ret == 0:
                        shutil.rmtree(default_bootstrap_root, ignore_errors = True)
                        options.bootstrap = default_bootstrap_root
                    else:
                        raise FatalError("Failed to rm %s, please ensure there isn't any other process accessing some directories under %s" % (default_bootstrap_root, default_bootstrap_root))
                options.buildbootstrap = True
    
    if options.buildbootstrap:
        if not options.bootstrap:
            raise FatalError("Please use -b | --build-bootstrap with -B | --bootstrap together")
        elif not os.path.exists(options.bootstrap):
            try:
                os.makedirs(options.bootstrap)
            except OSError, (err, msg):
                raise FatalError(msg)
        elif os.path.isdir(options.bootstrap) and len(os.listdir(options.bootstrap)) != 0:
            raise FatalError("bootstrap must be an empty or non-existed directory.")

    if not options.buildbootstrap and options.bootstrap:
        if not os.path.isdir(options.bootstrap) or not imgcreate.bootstrap.isbootstrap(options.bootstrap):
            raise FatalError("Please specify a workable bootstrap env")
    if options.bootstrap:
        print "Run mode: bootstrap"
    else:
        print "Run mode: legacy"

    # Need to be update if new format added
    support_format = ('fs', 'livecd', 'liveusb', 'loop', 'raw', 'vmdk', 'vdi', 'ubi', 'jffs2', 'mrstnand', 'nand')
    if not options.format:
        options.format = get_siteconf_opt(siteconf, "main", "image_format")
    if options.format not in support_format:
        raise FatalError("Image format '%s' isn't supported " % options.format)

    if options.package not in ("none", "tar", "tar.gz", "tar.bz2"):
        raise FatalError("Package format '%s' isn't supported" % options.package)

    if options.format == 'nand':
        print "WARNING: Image format 'nand' will be deprecated soon, and format 'mrstnand' is preferred."
        options.format = 'mrstnand'

    """ Get global config from site config, but command line option has high priority, it will override settings from site config """
    if not options.tmpdir:
        options.tmpdir = "/var/tmp"
        value = get_siteconf_diropt(siteconf, "tmpdir")
        if value:
            options.tmpdir = value
 
    if not options.cachedir:
        options.cachedir = None
        value = get_siteconf_diropt(siteconf, "cachedir")
        if value:
            options.cachedir = value
    else:
        options.cachedir = os.path.abspath(os.path.expanduser(options.cachedir))

    destdir = "."
    if not options.outdir:
        value = get_siteconf_diropt(siteconf, "outdir") 
        if value:
            destdir = value
    else:
        destdir = options.outdir
    destdir = os.path.abspath(os.path.expanduser(destdir))

    if options.release and options.run_mode == 0:
        if options.format not in ["livecd", "liveusb"]:
            options.package = "tar.bz2"
        options.record_pkgs = "name"
        if not options.prefix:
            options.prefix = "meego"
        if not options.suffix:
            options.suffix = options.release
        meegovert = ["handset", "netbook", "tablet", "ivi", "cetv", "core"]
        meegoarch = ["ia32", "armv5tel", "armv7l"]
        base = os.path.basename(options.config)
        ksname = base.split(".")[0]
        ksnamec = ksname.split("-")
        if ksnamec[0] not in meegovert or ksnamec[1] not in meegoarch:
            raise FatalError("Configuration file %s does not follow naming conventions: $VERTICAL-$ARCH-$VARIANT " %(options.config))

        options.outdir = "%s/%s/%s/images/%s-%s" %(destdir, options.release, ksnamec[0], options.prefix, ksname)
        destdir = options.outdir

    if not os.path.exists(destdir):
        imgcreate.fs.makedirs(destdir)

    imgcreate.misc.set_proxies()

    """ proxy settings from stie config override proxy settings from environment variables """
    proxy = None
    no_proxy = None
    if siteconf and siteconf.has_section("main") and siteconf.has_option("main", "proxy"):
        proxy = siteconf.get("main", "proxy")
    if siteconf and siteconf.has_section("main") and siteconf.has_option("main", "no_proxy"):
        no_proxy = siteconf.get("main", "no_proxy")
    if proxy or no_proxy:
        imgcreate.misc.set_proxies(proxy, no_proxy)

    """ Get repos from site config """
    site_repos = imgcreate.misc.get_repostrs_from_siteconf(siteconf)

    """ Give a temporary name for repos without name """
    if options.addrepos:
        for i in range(len(options.addrepos)):
            if options.addrepos[i].split(":")[0] in ("http", "https", "ftp", "ftps"):
                options.addrepos[i] = "name:%s,baseurl:%s" % (imgcreate.misc.get_temp_reponame(options.addrepos[i]), options.addrepos[i])
    else:
       options.addrepos = []

    """ Must call get_metadata_from_repos firstly to get repo metadata """
    ks_repos = []
    if options.config:
        try:
            ks = imgcreate.read_kickstart(options.config)
            ks_repos = imgcreate.misc.get_repostrs_from_ks(ks)
        except imgcreate.CreatorError, e:
            raise FatalError("unable to load kickstart file '%s' : %s" % (options.config, e))
    try:
        repometadata = imgcreate.misc.get_metadata_from_repos(options.addrepos + site_repos + ks_repos, options.cachedir)
        if not repometadata:
            raise FatalError("Not any repo is available")
        release_no = imgcreate.misc.get_release_no(repometadata, distro_name.lower())
        target_archlist = imgcreate.misc.get_arch(repometadata)
        print target_archlist
    except imgcreate.CreatorError, e:
        debugger.record_callstack()
        raise FatalError("failed to create image : %s" % e)
    except OSError, e:
        raise FatalError("failed to create image : %s" % e)
    print "%s release %s" % (distro_name, release_no)

    if not options.config:
        try:
            ksfiles = imgcreate.misc.get_kickstarts_from_repos(repometadata)
        except imgcreate.CreatorError, e:
            debugger.record_callstack()
            raise FatalError("failed to create image : %s" % e)
        if not ksfiles:
            """ Didn't find kickstart files from repo, so try to get it from command line option """
            raise FatalError("Your repos do not provide any kickstart files, please provide a kickstart file using -c or --config option.")
        else:
            if not options.default_ks:
                options.default_ks = get_siteconf_opt(siteconf, "main", "default_ks")
            if options.default_ks:
                for ksfile in ksfiles:
                    if options.default_ks == os.path.basename(ksfile["filename"]):
                        options.config = ksfile["filename"]
                        break
                if not options.config:
                    raise FatalError("Failed to find default kickstart file %s" % options.default_ks)
            else:
                options.config = imgcreate.misc.select_ks(ksfiles)

    try:
        ks = imgcreate.read_kickstart(options.config)
    except imgcreate.CreatorError, e:
        debugger.record_callstack()
        raise FatalError("unable to load kickstart file '%s' : %s" % (options.config, e))


    # Parse patterns if exists
    if not options.use_comps:
        options.use_comps = get_siteconf_opt(siteconf, "main", "use_comps")
        if options.use_comps != "1":
            options.use_comps = False
        else:
            options.use_comps = True
    imgcreate.kickstart.support_patterns(ks, repometadata, options.use_comps)

    for siterepo in site_repos:
        try:
           imgcreate.kickstart.add_repo(ks, imgcreate.misc.get_repostr(siterepo, siteconf))
        except ValueError, msg:
           raise FatalError("Please provide valid repo string")

    """ Get repostrs from kickstart """
    ks_repos = imgcreate.misc.get_repostrs_from_ks(ks)
    imgcreate.kickstart.remove_all_repos(ks) # Need to automatically set proxy for repos or remap repos
    for ksrepo in ks_repos:
        try:
           imgcreate.kickstart.add_repo(ks, imgcreate.misc.get_repostr(ksrepo, siteconf))
        except ValueError, msg:
           raise FatalError("Please provide valid repo string")

    """ Set additional repos """
    if options.addrepos:
        for addrepo in options.addrepos:
            try:
                imgcreate.kickstart.add_repo(ks, imgcreate.misc.get_repostr(addrepo, siteconf))
            except ValueError, msg:
                raise FatalError("Please provide valid repo string")

    """ Remove duplicate repos """
    imgcreate.kickstart.remove_duplicate_repos(ks)

    if not options.prefix:
        options.prefix = "%s-" % distro_name.lower()
    else:
        options.prefix = "%s-" %options.prefix

    if not options.suffix:
        options.suffix = "%s.%s" %(release_no, time.strftime("%Y%m%d.%H%M"))

    name = imgcreate.build_name(options.config, options.prefix, suffix=options.suffix)

    target_arch = options.arch
    need_convert = False
    if options.bootstrap and options.format in ("vmdk", "vdi"):
        imgcreate.bootstrap.check_depends(options.format)
        need_convert = True
        imgfmt = options.format
        options.format = "raw"
        pkgfmt = options.package
        options.package = "none"

    if options.buildbootstrap:
        # ensure a cachedir is available
        rmcachedir = False
        if not options.cachedir:
            try:
                options.cachedir = tempfile.mkdtemp(dir = options.tmpdir,
                                               prefix = "bootstrapcache-")
                rmcachedir = True
            except OSError, (err, msg):
                raise CreatorError("Failed create bootstrap cache directory in %s: %s" %
                                  (options.tmpdir, msg))

        # Use main repo from command line option
        proxies = {}
        reponame = None
        for repo in ks.handler.repo.repoList:
            if repo.name == options.mainrepo:
                reponame = repo.name
                repourl = repo.baseurl
                if repo.proxy:
                    proxies = {"http":repo.proxy,"https":repo.proxy, "ftp":repo.proxy, "ftps":repo.proxy}
                break

        # guess main repo if not provided
        if options.arch:
            for target_arch in target_archlist:
                if target_arch.startswith(options.arch.strip()):
                    break
        if not reponame:
            for repo in ks.handler.repo.repoList:
                if repo.proxy:
                    proxies = {"http":repo.proxy,"https":repo.proxy, "ftp":repo.proxy, "ftps":repo.proxy}
                imgcreate.bootstrap.get_repo_metadata(repo.baseurl, options.cachedir, repo.name, proxies, arch = target_arch)
                if imgcreate.bootstrap.is_mainrepo(options.cachedir, repo.name):
                    reponame = repo.name
                    repourl = repo.baseurl
                    break
            if not reponame:
                raise FatalError("Please specify main repo name using --mainrepo option.")
        else:
            sqlitedb = imgcreate.bootstrap.get_repo_metadata(repourl, options.cachedir, reponame, proxies, arch = target_arch)
        imgcreate.bootstrap.build_bootstrap(repourl, options.cachedir, reponame, options.bootstrap, proxies, arch = target_arch)
        if rmcachedir:
            shutil.rmtree(options.cachedir, ignore_errors = True)


    if options.bootstrap:
        options.outdir = os.path.abspath(os.path.expanduser(destdir))
        if options.cachedir:
            options.cachedir = os.path.abspath(os.path.expanduser(options.cachedir))
        options.tmpdir = os.path.abspath(os.path.expanduser(options.tmpdir))
        oldconfig = options.config
        fd = open(options.bootstrap + "/root/" + os.path.basename(options.config), "w")
        fd.write(ks.handler.__str__())
        fd.close()
        options.config = "/root/" + os.path.basename(options.config)

        argv = rebuild_argv(sys.argv, options)
        mypipe = tempfile.mktemp(".mic2pipe", ".mic2-", destdir)
        argv.append("--pipe=%s" % mypipe)
        if need_convert:
            image_info = tempfile.mktemp(".mic2info", ".mic2-", destdir)
            argv.append("--image-info=%s" % image_info)
        print argv
        bindmounts = ""
        for repo in ks.handler.repo.repoList:
            if repo.baseurl.startswith("file:///"):
                repodir = repo.baseurl.replace("file://", "")
                if bindmounts.find(repodir) < 0:
                    bindmounts += "%s;" % repodir
        bindmounts += "%s;%s" % (options.outdir, options.tmpdir)
        if options.cachedir:
            bindmounts = bindmounts + ";%s" % options.cachedir
        run_in_bootstrap(options.bootstrap, argv, bindmounts, arch = target_arch)
        # For the case with release option, destdir is changed, so get it
        for line in open(mypipe).xreadlines():
            if line.find("destdir=") != -1:
                destdir = line[line.find("destdir=") + 8:-1]
            if line.find("package=") != -1:
                pkgfmt = line[line.find("package=") + 8:-1]
        os.unlink(mypipe)
        if need_convert:
            imgfile = imgcreate.bootstrap.get_imgfile(image_info)
            srcdir = os.path.dirname(imgfile)
            dstdir = srcdir[0:-3] + imgfmt
            shutil.move(srcdir, dstdir)
            imgfile = dstdir + "/" + os.path.basename(imgfile)
            outimages = imgcreate.bootstrap.convert_to(imgfile, imgfmt)
            dst = imgcreate.bootstrap.package_image(outimages, imgfmt, destdir, pkgfmt)
            if options.release:
                imgcreate.create_release(oldconfig, destdir, name)
            if dst:
                outimages.append(dst)
            if options.release:
                outimages = []
                for f in os.listdir(destdir):
                    outimages.append(os.path.join(destdir, f))
            imgcreate.bootstrap.print_imginfo(outimages)
            print "Finished."
        # Save original kickstart file
        shutil.copy(oldconfig, destdir + "/%s.ks" % name)
        sys.exit(0)


    if options.format == "fs":
        creator = imgcreate.FsImageCreator(ks, name)
        creator._fstype = None
    elif options.format in ("livecd", "liveusb"):
        fs_label = imgcreate.build_name(options.config,
                                        "%s-" % options.prefix,
                                        maxlen = imgcreate.FSLABEL_MAXLEN,
                                        suffix = "%s-%s" %(os.uname()[4], time.strftime("%Y%m%d%H%M")))

        logging.info("Using label '%s' and name '%s'" % (fs_label, name))
        try:
            if options.format == "liveusb" and not options.interactive:
                creator = imgcreate.LiveUSBImageCreator(ks, name, fs_label)
                creator.fstype = options.fstype
                if creator.fstype != "vfat" and creator.fstype != "ext3":
                    raise FatalError("file system type for live USB image  must be vfat or ext3")
            else:
                creator = imgcreate.LiveImageCreator(ks, name, fs_label)
            if options.format == "liveusb":
                creator.overlaysizemb = options.overlay_size_mb
                if creator.overlaysizemb < 0:
                    raise FatalError("Overlay size must be greater than 0")
        except imgcreate.CreatorError, e:
            debugger.record_callstack()
            raise FatalError("failed to create image : %s" % e)
        finally:
            creator.cleanup()

        creator.skip_compression = options.skip_compression
        creator.skip_minimize = options.skip_minimize
    elif options.format == "loop":
        creator = imgcreate.LoopImageCreator(ks, name)
    elif options.format == "mrstnand":
        creator = appcreate.NandImageCreator(ks, name,
                                initrd_url = options.initrd_url,
                                initrd_path = options.initrd_path,
                                kernel_url = options.kernel_url,
                                kernel_path = options.kernel_path,
                                kernel_rpm_url = options.kernel_rpm_url,
                                kernel_rpm_path = options.kernel_rpm_path,
                                bootimg_only = options.bootimg_only)
    elif options.format == "ubi":
        creator = imgcreate.UbiImageCreator(ks, name)
    elif options.format == "jffs2":
        creator = imgcreate.Jffs2ImageCreator(ks, name)
    elif options.format in ("raw", "vmdk", "vdi"):
        creator = appcreate.ApplianceImageCreator(ks, name, options.format, 512, 1)
    else:
        raise FatalError("You have to specify an image format")

    creator.tmpdir = options.tmpdir
    creator._alt_initrd_name = options.alt_initrd_name
    creator._recording_pkgs = options.record_pkgs
    creator._local_pkgs_path = options.local_pkgs_path
    creator._genchecksum = options.genchecksum
    creator.distro_name = distro_name

    if options.arch:
        arch_set = False
        for target_arch in target_archlist:
            if target_arch.startswith(options.arch.strip()):
                creator.set_target_arch(target_arch)
                print "Target arch: %s" % creator.target_arch
                arch_set = True
                break
   
        if not arch_set:
            raise FatalError("Given arch '%s' is not found from the repositories." % options.arch.strip())

    imgname = creator.name
    for part in ks.handler.partition.partitions:
        if part.fstype and part.fstype == "btrfs":
            creator._dep_checks.append(("/sbin/mkfs.btrfs",))
            break
    try:
        creator.check_depend_tools()
        creator.mount(None, options.cachedir)
        creator.install()
        creator.configure()
        if options.save_kernel:
            creator.save_kernel(destdir)
        creator.launch_shell(options.give_shell)
        creator.unmount()
        if options.format in ("raw", "vmdk", "vdi"):
            creator.package(destdir, "none", None)
        else:
            creator.package(destdir)
        outimage = creator.outimage
        if not options.image_info:
            creator.package_output(options.format, destdir, options.package)
            if options.release:
                creator.release_output(options.config, destdir, name)
            creator.print_outimage_info()
            outimage = creator.outimage
        else:
            imgcreate.bootstrap.save_imginfo(outimage, options.image_info)
        if options.pipe:
            fd = open(options.pipe, "w");
            fd.write("destdir=%s\n" % destdir)
            if options.release and options.package:
                fd.write("package=%s\n" % options.package)
            fd.close()
    except imgcreate.CreatorError, e:
        debugger.record_callstack()
        raise FatalError("failed to create image : %s" % e)
    finally:
        creator.cleanup()


    if options.format == "liveusb" and options.interactive:
        mypath = os.path.abspath(sys.argv[0])
        mypath = os.path.dirname(mypath)
        isotodisk = mypath + "/mic-livecd-iso-to-disk"
        if not os.path.isfile(isotodisk):
            raise FatalError("Error mic-livecd-iso-to-disk doesn't exist")
        args = [isotodisk, "--reset-mbr", "--overlay-size-mb", "%d" % creator.overlaysizemb, outimage[0]]
        ret = subprocess.call(args)
        if ret != 0:
            raise FatalError("failed to create Live USB : '%s' exited with error (%d)" % (string.join(args, " "), ret))

    if not options.image_info:
            print "Finished."

    return 0


COLOR_BLACK = "\033[00m"
COLOR_RED =   "\033[1;31m"
if __name__ == "__main__":
    try:
        ret = main()
        sys.exit(ret)
    except FatalError, e:
        print >> sys.stderr, "\n%sError: %s%s\n" % (COLOR_RED, e, COLOR_BLACK)
        debugger.record_callstack()
        debugger.dump_debuginfo()
        sys.exit(1)