982623fbfb8b3f515551d958f397725779d82748
[grml2usb.git] / grml2usb
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 """
4 grml2usb
5 ~~~~~~~~
6
7 This script installs a grml system (either a running system or ISO[s]) to a USB device
8
9 :copyright: (c) 2009 by Michael Prokop <mika@grml.org>
10 :license: GPL v2 or any later version
11 :bugreports: http://grml.org/bugs/
12
13 """
14
15 from __future__ import with_statement
16 from optparse import OptionParser
17 from inspect import isroutine, isclass
18 import datetime, logging, os, re, subprocess, sys, tempfile, time
19
20 # global variables
21 PROG_VERSION = "0.9.2(pre1)"
22 MOUNTED = set()  # register mountpoints
23 TMPFILES = set() # register tmpfiles
24 DATESTAMP = time.mktime(datetime.datetime.now().timetuple()) # unique identifier for syslinux.cfg
25
26 # cmdline parsing
27 USAGE = "Usage: %prog [options] <[ISO[s] | /live/image]> </dev/sdX#>\n\
28 \n\
29 %prog installs a grml ISO to an USB device to be able to boot from it.\n\
30 Make sure you have at least one grml ISO or a running grml system (/live/image),\n\
31 syslinux (just run 'aptitude install syslinux' on Debian-based systems)\n\
32 and root access. Further information can be found in: man grml2usb"
33
34 # pylint: disable-msg=C0103
35 parser = OptionParser(usage=USAGE)
36 parser.add_option("--bootoptions", dest="bootoptions",
37                   action="store", type="string",
38                   help="use specified bootoptions as default")
39 parser.add_option("--bootloader-only", dest="bootloaderonly", action="store_true",
40                   help="do not copy files but just install a bootloader")
41 parser.add_option("--copy-only", dest="copyonly", action="store_true",
42                   help="copy files only but do not install bootloader")
43 parser.add_option("--dry-run", dest="dryrun", action="store_true",
44                   help="avoid executing commands")
45 parser.add_option("--fat16", dest="fat16", action="store_true",
46                   help="format specified partition with FAT16")
47 parser.add_option("--force", dest="force", action="store_true",
48                   help="force any actions requiring manual interaction")
49 parser.add_option("--grub", dest="grub", action="store_true",
50                   help="install grub bootloader instead of syslinux")
51 parser.add_option("--initrd", dest="initrd", action="store", type="string",
52                   help="install specified initrd instead of the default [TODO]")
53 parser.add_option("--kernel", dest="kernel", action="store", type="string",
54                   help="install specified kernel instead of the default [TODO]")
55 parser.add_option("--lilo", dest="lilo",  action="store", type="string",
56                   help="lilo executable to be used for installing MBR")
57 parser.add_option("--quiet", dest="quiet", action="store_true",
58                   help="do not output anything but just errors on console")
59 parser.add_option("--skip-addons", dest="skipaddons", action="store_true",
60                   help="do not install /boot/addons/ files")
61 parser.add_option("--skip-mbr", dest="skipmbr", action="store_true",
62                   help="do not install a master boot record (MBR) on the device")
63 parser.add_option("--squashfs", dest="squashfs", action="store", type="string",
64                   help="install specified squashfs file instead of the default [TODO]")
65 parser.add_option("--uninstall", dest="uninstall", action="store_true",
66                   help="remove grml ISO files from specified device [TODO]")
67 parser.add_option("--verbose", dest="verbose", action="store_true",
68                   help="enable verbose mode")
69 parser.add_option("-v", "--version", dest="version", action="store_true",
70                   help="display version and exit")
71 (options, args) = parser.parse_args()
72
73
74 class CriticalException(Exception):
75     """Throw critical exception if the exact error is not known but fatal."
76
77     @Exception: message"""
78     pass
79
80
81 def cleanup():
82     """Cleanup function to make sure there aren't any mounted devices left behind.
83     """
84
85     logging.info("Cleaning up before exiting...")
86     proc = subprocess.Popen(["sync"])
87     proc.wait()
88
89     try:
90         for device in MOUNTED:
91             unmount(device, "")
92     # ignore: RuntimeError: Set changed size during iteration
93     except RuntimeError:
94         logging.debug('caught expection RuntimeError, ignoring')
95
96
97 def register_tmpfile(path):
98     """TODO
99     """
100
101     TMPFILES.add(path)
102
103
104 def unregister_tmpfile(path):
105     """TODO
106     """
107
108     if path in TMPFILES:
109         TMPFILES.remove(path)
110
111
112 def register_mountpoint(target):
113     """TODO
114     """
115
116     MOUNTED.add(target)
117
118
119 def unregister_mountpoint(target):
120     """TODO
121     """
122
123     if target in MOUNTED:
124         MOUNTED.remove(target)
125
126
127 def get_function_name(obj):
128     """Helper function for use in execute() to retrive name of a function
129
130     @obj: the function object
131     """
132     if not (isroutine(obj) or isclass(obj)):
133         obj = type(obj)
134     return obj.__module__ + '.' + obj.__name__
135
136
137 def execute(f, *exec_arguments):
138     """Wrapper for executing a command. Either really executes
139     the command (default) or when using --dry-run commandline option
140     just displays what would be executed."""
141     # usage: execute(subprocess.Popen, (["ls", "-la"]))
142     # TODO: doesn't work for proc = execute(subprocess.Popen...() -> any ideas?
143     if options.dryrun:
144         # pylint: disable-msg=W0141
145         logging.debug('dry-run only: %s(%s)' % (get_function_name(f), ', '.join(map(repr, exec_arguments))))
146     else:
147         # pylint: disable-msg=W0142
148         return f(*exec_arguments)
149
150
151 def is_exe(fpath):
152     """Check whether a given file can be executed
153
154     @fpath: full path to file
155     @return:"""
156     return os.path.exists(fpath) and os.access(fpath, os.X_OK)
157
158
159 def which(program):
160     """Check whether a given program is available in PATH
161
162     @program: name of executable"""
163     fpath = os.path.split(program)[0]
164     if fpath:
165         if is_exe(program):
166             return program
167     else:
168         for path in os.environ["PATH"].split(os.pathsep):
169             exe_file = os.path.join(path, program)
170             if is_exe(exe_file):
171                 return exe_file
172
173     return None
174
175
176 def search_file(filename, search_path='/bin' + os.pathsep + '/usr/bin'):
177     """Given a search path, find file
178
179     @filename: name of file to search for
180     @search_path: path where searching for the specified filename"""
181     file_found = 0
182     paths = search_path.split(os.pathsep)
183     current_dir = '' # make pylint happy :)
184     for path in paths:
185         # pylint: disable-msg=W0612
186         for current_dir, directories, files in os.walk(path):
187             if os.path.exists(os.path.join(current_dir, filename)):
188                 file_found = 1
189                 break
190     if file_found:
191         return os.path.abspath(os.path.join(current_dir, filename))
192     else:
193         return None
194
195
196 def check_uid_root():
197     """Check for root permissions"""
198     if not os.geteuid()==0:
199         sys.exit("Error: please run this script with uid 0 (root).")
200
201
202 def mkfs_fat16(device):
203     """Format specified device with VFAT/FAT16 filesystem.
204
205     @device: partition that should be formated"""
206
207     # syslinux -d boot/isolinux /dev/sdb1
208     logging.info("Formating partition with fat16 filesystem")
209     logging.debug("mkfs.vfat -F 16 %s" % device)
210     proc = subprocess.Popen(["mkfs.vfat", "-F", "16", device])
211     proc.wait()
212     if proc.returncode != 0:
213         raise Exception("error executing mkfs.vfat")
214
215
216 def generate_main_grub2_config(grml_flavour, install_partition, bootoptions):
217     """Generate grub2 configuration for use via grub.cfg
218
219     TODO
220
221     @grml_flavour: name of grml flavour the configuration should be generated for"""
222
223     local_datestamp = DATESTAMP
224
225     return("""\
226 set default=0
227 set timeout=5
228
229 insmod fat
230
231 insmod png
232 if background_image (hd0, %(install_partition)s)/boot/grub/grml.png ; then
233   set color_normal=black/black
234   set color_highlight=magenta/black
235 else
236   set menu_color_normal=cyan/blue
237   set menu_color_highlight=white/blue
238 fi
239
240 ## main grub2 configuration - generated by grml2usb [main config generated at: %(local_datestamp)s]
241 menuentry "%(grml_flavour)s (default)" {
242     set root=(hd0,%(install_partition)s)
243     linux   /boot/release/%(grml_flavour)s/linux26 apm=power-off lang=us vga=791 quiet boot=live nomce module=%(grml_flavour)s %(bootoptions)s
244     initrd  /boot/release/%(grml_flavour)s/initrd.gz
245 }
246
247 menuentry "Memory test (memtest86+)" {
248    linux   /boot/addons/memtest
249 }
250
251 menuentry "Grub - all in one image" {
252    linux   /boot/addons/memdisk
253    initrd  /boot/addons/allinone.img
254 }
255
256 menuentry "FreeDOS" {
257    linux   /boot/addons/memdisk
258    initrd  /boot/addons/balder10.imz
259 }
260
261 #menuentry "Operating System on first partition of first disk" {
262 #    set root=(hd0,1)
263 #    chainloader +1
264 #}
265 #
266 #menuentry "Operating System on second partition of first disk" {
267 #    set root=(hd0,2)
268 #    chainloader +1
269 #}
270 #
271 #menuentry "Operating System on first partition of second disk" {
272 #    set root=(hd1,1)
273 #    chainloader +1
274 #}
275 #menuentry "Operating System on second partition of second disk" {
276 #    set root=(hd1,2)
277 #    chainloader +1
278 #}
279
280 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions, 'install_partition': install_partition } )
281
282
283 def generate_flavour_specific_grub2_config(grml_flavour, install_partition, bootoptions):
284     """Generate grub2 configuration for use via grub.cfg
285
286     TODO
287
288     @grml_flavour: name of grml flavour the configuration should be generated for"""
289
290     local_datestamp = DATESTAMP
291
292     return("""\
293 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
294 menuentry "%(grml_flavour)s" {
295     set root=(hd0,%(install_partition)s)
296     linux  /boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s %(bootoptions)s
297     initrd /boot/release/%(grml_flavour)s/initrd.gz
298 }
299
300 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
301 menuentry "%(grml_flavour)s2ram" {
302     set root=(hd0,%(install_partition)s)
303     linux  /boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s toram=%(grml_flavour)s %(bootoptions)s
304     initrd /boot/release/%(grml_flavour)s/initrd.gz
305
306 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
307 menuentry "%(grml_flavour)s-debug" {
308     set root=(hd0,%(install_partition)s)
309     linux /boot/release/%(grml_flavour)s/linux26
310     initrd /boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s debug boot=live initcall_debug%(bootoptions)s
311 }
312
313 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
314 menuentry "%(grml_flavour)s-x" {
315     set root=(hd0,%(install_partition)s)
316     linux  /boot/release/%(grml_flavour)s/linux26
317     initrd /boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s startx=wm-ng %(bootoptions)s
318 }
319
320 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
321 menuentry "%(grml_flavour)s-nofb" {
322     set root=(hd0,%(install_partition)s)
323     linux  /boot/release/%(grml_flavour)s/linux26
324     initrd /boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s vga=normal video=ofonly %(bootoptions)s
325 }
326
327 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
328 menuentry "%(grml_flavour)s-failsafe" {
329     set root=(hd0,%(install_partition)s)
330     linux /boot/release/%(grml_flavour)s/linux26
331     initrd /boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s vga=normal lang=us boot=live noautoconfig atapicd noacpi acpi=off nomodules nofirewire noudev nousb nohotplug noapm nopcmcia maxcpus=1 noscsi noagp nodma ide=nodma noswap nofstab nosound nogpm nosyslog nodhcp nocpu nodisc nomodem xmodule=vesa noraid nolvm %(bootoptions)s
332 }
333
334 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
335 menuentry "%(grml_flavour)s-forensic" {
336     set root=(hd0,%(install_partition)s)
337     linux /boot/release/%(grml_flavour)s/linux26
338     initrd /boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s nofstab noraid nolvm noautoconfig noswap raid=noautodetect %(bootoptions)s
339 }
340
341 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
342 menuentry "%(grml_flavour)s-serial" {
343     set root=(hd0,%(install_partition)s)
344     linux /boot/release/%(grml_flavour)s/linux26
345     initrd /boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s vga=normal video=vesafb:off console=tty1 console=ttyS0,9600n8 %(bootoptions)s
346 }
347
348 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions, 'install_partition': install_partition } )
349
350
351 def generate_grub1_config(grml_flavour, install_partition, bootoptions):
352     """Generate grub1 configuration for use via menu.lst
353
354     @grml_flavour: name of grml flavour the configuration should be generated for"""
355
356     local_datestamp = DATESTAMP
357
358     return("""\
359 # misc options:
360 timeout 30
361 # color red/blue green/black
362 splashimage=/boot/grub/splash.xpm.gz
363 foreground  = 000000
364 background  = FFCC33
365
366 # define entries:
367 title %(grml_flavour)s  - Default boot (using 1024x768 framebuffer)
368 kernel /boot/release/%(grml_flavour)s/linux26 apm=power-off lang=us vga=791 quiet boot=live nomce module=%(grml_flavour)s
369 initrd /boot/release/%(grml_flavour)s/initrd.gz
370
371 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
372
373
374 def generate_isolinux_splash(grml_flavour):
375     """Generate bootsplash for isolinux/syslinux
376
377     @grml_flavour: name of grml flavour the configuration should be generated for"""
378
379     # TODO: adjust last bootsplash line (the one following the "Some information and boot ...")
380
381     grml_name = grml_flavour
382
383     return("""\
384 \ f17\f\18/boot/syslinux/logo.16
385
386 Some information and boot options available via keys F2 - F10. http://grml.org/
387 %(grml_name)s
388 """ % {'grml_name': grml_name} )
389
390
391 def generate_main_syslinux_config(grml_flavour, bootoptions):
392     """Generate main configuration for use in syslinux.cfg
393
394     @grml_flavour: name of grml flavour the configuration should be generated for
395     @bootoptions: bootoptions that should be used as a default"""
396
397     local_datestamp = DATESTAMP
398
399     return("""\
400 ## main syslinux configuration - generated by grml2usb [main config generated at: %(local_datestamp)s]
401 # use this to control the bootup via a serial port
402 # SERIAL 0 9600
403 DEFAULT grml
404 TIMEOUT 300
405 PROMPT 1
406 DISPLAY /boot/syslinux/boot.msg
407 F1 /boot/syslinux/boot.msg
408 F2 /boot/syslinux/f2
409 F3 /boot/syslinux/f3
410 F4 /boot/syslinux/f4
411 F5 /boot/syslinux/f5
412 F6 /boot/syslinux/f6
413 F7 /boot/syslinux/f7
414 F8 /boot/syslinux/f8
415 F9 /boot/syslinux/f9
416 F10 /boot/syslinux/f10
417 ## end of main configuration
418
419 ## global configuration
420 # the default option (using %(grml_flavour)s)
421 LABEL  grml
422 KERNEL /boot/release/%(grml_flavour)s/linux26
423 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s %(bootoptions)s
424
425 # memtest
426 LABEL  memtest
427 KERNEL /boot/addons/memtest
428
429 # grub
430 LABEL grub
431 MENU LABEL grub
432 KERNEL /boot/addons/memdisk
433 APPEND initrd=/boot/addons/allinone.img
434
435 # dos
436 LABEL dos
437 MENU LABEL dos
438 KERNEL /boot/addons/memdisk
439 APPEND initrd=/boot/addons/balder10.imz
440
441 ## end of global configuration
442 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
443
444
445 def generate_flavour_specific_syslinux_config(grml_flavour, bootoptions):
446     """Generate flavour specific configuration for use in syslinux.cfg
447
448     @grml_flavour: name of grml flavour the configuration should be generated for
449     @bootoptions: bootoptions that should be used as a default"""
450
451     local_datestamp = DATESTAMP
452
453     return("""\
454
455 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
456 LABEL  %(grml_flavour)s
457 KERNEL /boot/release/%(grml_flavour)s/linux26
458 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s %(bootoptions)s
459
460 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
461 LABEL  %(grml_flavour)s2ram
462 KERNEL /boot/release/%(grml_flavour)s/linux26
463 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s toram=%(grml_flavour)s %(bootoptions)s
464
465 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
466 LABEL  %(grml_flavour)s-debug
467 KERNEL /boot/release/%(grml_flavour)s/linux26
468 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s debug boot=live initcall_debug%(bootoptions)s
469
470 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
471 LABEL  %(grml_flavour)s-x
472 KERNEL /boot/release/%(grml_flavour)s/linux26
473 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s startx=wm-ng %(bootoptions)s
474
475 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
476 LABEL  %(grml_flavour)s-nofb
477 KERNEL /boot/release/%(grml_flavour)s/linux26
478 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s vga=normal video=ofonly %(bootoptions)s
479
480 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
481 LABEL  %(grml_flavour)s-failsafe
482 KERNEL /boot/release/%(grml_flavour)s/linux26
483 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s vga=normal lang=us boot=live noautoconfig atapicd noacpi acpi=off nomodules nofirewire noudev nousb nohotplug noapm nopcmcia maxcpus=1 noscsi noagp nodma ide=nodma noswap nofstab nosound nogpm nosyslog nodhcp nocpu nodisc nomodem xmodule=vesa noraid nolvm %(bootoptions)s
484
485 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
486 LABEL  %(grml_flavour)s-forensic
487 KERNEL /boot/release/%(grml_flavour)s/linux26
488 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s nofstab noraid nolvm noautoconfig noswap raid=noautodetect %(bootoptions)s
489
490 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
491 LABEL  %(grml_flavour)s-serial
492 KERNEL /boot/release/%(grml_flavour)s/linux26
493 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s vga=normal video=vesafb:off console=tty1 console=ttyS0,9600n8 %(bootoptions)s
494 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
495
496
497 def install_grub(device):
498     """Install grub on specified device.
499
500     @mntpoint: mountpoint of device where grub should install its files to
501     @device: partition where grub should be installed to"""
502
503     if options.dryrun:
504         logging.info("Would execute grub-install [--root-directory=mount_point] %s now.", device)
505     else:
506         device_mountpoint = tempfile.mkdtemp()
507         register_tmpfile(device_mountpoint)
508         try:
509             mount(device, device_mountpoint, "")
510             logging.debug("grub-install --root-directory=%s %s", device_mountpoint, device)
511             proc = subprocess.Popen(["grub-install", "--root-directory=%s" % device_mountpoint, device])
512             proc.wait()
513             if proc.returncode != 0:
514                 raise Exception("error executing grub-install")
515         except CriticalException, error:
516             logging.critical("Fatal: %s" % error)
517             cleanup()
518             sys.exit(1)
519
520         finally:
521             unmount(device_mountpoint, "")
522             os.rmdir(device_mountpoint)
523             unregister_tmpfile(device_mountpoint)
524
525
526 def install_syslinux(device):
527     """Install syslinux on specified device.
528
529     @device: partition where syslinux should be installed to"""
530
531     if options.dryrun:
532         logging.info("Would install syslinux as bootloader on %s", device)
533         return 0
534
535     # syslinux -d boot/isolinux /dev/sdb1
536     logging.info("Installing syslinux as bootloader")
537     logging.debug("syslinux -d boot/syslinux %s" % device)
538     proc = subprocess.Popen(["syslinux", "-d", "boot/syslinux", device])
539     proc.wait()
540     if proc.returncode != 0:
541         raise CriticalException("Error executing syslinux (either try --fat16 or --grub?)")
542
543
544 def install_bootloader(device):
545     """Install bootloader on specified device.
546
547     @device: partition where bootloader should be installed to"""
548
549     # Install bootloader on the device (/dev/sda),
550     # not on the partition itself (/dev/sda1)?
551     #if partition[-1:].isdigit():
552     #    device = re.match(r'(.*?)\d*$', partition).group(1)
553     #else:
554     #    device = partition
555
556     if options.grub:
557         install_grub(device)
558     else:
559         try:
560             install_syslinux(device)
561         except CriticalException, error:
562             logging.critical("Fatal: %s" % error)
563             cleanup()
564             sys.exit(1)
565
566
567 def install_lilo_mbr(lilo, device):
568     """TODO"""
569
570     # TODO: check out the *real* difference between:
571     # * mbr-install /dev/ice
572     # * lilo -S /dev/null -M /dev/ice ext && lilo -S /dev/null -A /dev/ice 1
573     # * cat /usr/lib/syslinux/mbr.bin > /dev/ice
574     # * syslinux -sf /dev/iceX
575     # * ...?
576
577     # to support -A for extended partitions:
578     logging.info("Installing MBR")
579     logging.debug("%s -S /dev/null -M %s ext" % (lilo, device))
580     proc = subprocess.Popen([lilo, "-S", "/dev/null", "-M", device, "ext"])
581     proc.wait()
582     if proc.returncode != 0:
583         raise Exception("error executing lilo")
584
585     # activate partition:
586     logging.debug("%s -S /dev/null -A %s 1" % (lilo, device))
587     proc = subprocess.Popen([lilo, "-S", "/dev/null", "-A", device, "1"])
588     proc.wait()
589     if proc.returncode != 0:
590         raise Exception("error executing lilo")
591
592
593 def install_syslinux_mbr(device):
594     """TODO"""
595
596     # lilo's mbr is broken, use the one from syslinux instead:
597     if not os.path.isfile("/usr/lib/syslinux/mbr.bin"):
598         raise Exception("/usr/lib/syslinux/mbr.bin can not be read")
599
600     logging.debug("cat /usr/lib/syslinux/mbr.bin > %s" % device)
601     try:
602         # TODO -> use Popen instead?
603         retcode = subprocess.call("cat /usr/lib/syslinux/mbr.bin > "+ device, shell=True)
604         if retcode < 0:
605             logging.critical("Error copying MBR to device (%s)" % retcode)
606     except OSError, error:
607         logging.critical("Execution failed:", error)
608
609
610 def install_mbr(device):
611     """Install a default master boot record on given device
612
613     @device: device where MBR should be installed to"""
614
615     if not is_writeable(device):
616         raise IOError("device not writeable for user")
617
618     # try to use system's lilo
619     if which("lilo"):
620         lilo = which("lilo")
621     else:
622         # otherwise fall back to our static version
623         from platform import architecture
624         if architecture()[0] == '64bit':
625             lilo = '/usr/share/grml2usb/lilo/lilo.static.amd64'
626         else:
627             lilo = '/usr/share/grml2usb/lilo/lilo.static.i386'
628     # finally prefer a specified lilo executable
629     if options.lilo:
630         lilo = options.lilo
631
632     if not is_exe(lilo):
633         raise Exception("lilo executable can not be execute")
634
635     if options.dryrun:
636         logging.info("Would install MBR running lilo and using syslinux.")
637         return 0
638
639     install_lilo_mbr(lilo, device)
640     install_syslinux_mbr(device)
641
642
643 def is_writeable(device):
644     """Check if the device is writeable for the current user
645
646     @device: partition where bootloader should be installed to"""
647
648     if not device:
649         return False
650         #raise Exception("no device for checking write permissions")
651
652     if not os.path.exists(device):
653         return False
654
655     return os.access(device, os.W_OK) and os.access(device, os.R_OK)
656
657
658 def mount(source, target, mount_options):
659     """Mount specified source on given target
660
661     @source: name of device/ISO that should be mounted
662     @target: directory where the ISO should be mounted to
663     @options: mount specific options"""
664
665     # notice: options.dryrun does not work here, as we have to
666     # locate files and identify the grml flavour
667     logging.debug("mount %s %s %s" % (mount_options, source, target))
668     proc = subprocess.Popen(["mount"] + list(mount_options) + [source, target])
669     proc.wait()
670     if proc.returncode != 0:
671         raise CriticalException("Error executing mount")
672     else:
673         logging.debug("register_mountpoint(%s)" % target)
674         register_mountpoint(target)
675
676
677 def unmount(target, unmount_options):
678     """Unmount specified target
679
680     @target: target where something is mounted on and which should be unmounted
681     @options: options for umount command"""
682
683     # make sure we unmount only already mounted targets
684     target_unmount = False
685     mounts = open('/proc/mounts').readlines()
686     mountstring = re.compile(".*%s.*" % re.escape(target))
687     for line in mounts:
688         if re.match(mountstring, line):
689             target_unmount = True
690
691     if not target_unmount:
692         logging.debug("%s not mounted anymore" % target)
693     else:
694         logging.debug("umount %s %s" % (list(unmount_options), target))
695         proc = subprocess.Popen(["umount"] + list(unmount_options) + [target])
696         proc.wait()
697         if proc.returncode != 0:
698             raise Exception("Error executing umount")
699         else:
700             logging.debug("unregister_mountpoint(%s)" % target)
701             unregister_mountpoint(target)
702
703
704 def check_for_usbdevice(device):
705     """Check whether the specified device is a removable USB device
706
707     @device: device name, like /dev/sda1 or /dev/sda
708     """
709
710     usbdevice = re.match(r'/dev/(.*?)\d*$', device).group(1)
711     usbdevice = os.path.realpath('/sys/class/block/' + usbdevice + '/removable')
712     if os.path.isfile(usbdevice):
713         is_usb = open(usbdevice).readline()
714         if is_usb == "1":
715             return 0
716         else:
717             return 1
718
719
720 def check_for_fat(partition):
721     """Check whether specified partition is a valid VFAT/FAT16 filesystem
722
723     @partition: device name of partition"""
724
725     try:
726         udev_info = subprocess.Popen(["/lib/udev/vol_id", "-t", partition],
727                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
728         filesystem = udev_info.communicate()[0].rstrip()
729
730         if udev_info.returncode == 2:
731             raise CriticalException("Failed to read device %s"
732                                     "(wrong UID/permissions or device not present?)" % partition)
733
734         if filesystem != "vfat":
735             raise CriticalException("Device %s does not contain a FAT16 partition." % partition)
736
737     except OSError:
738         raise CriticalException("Sorry, /lib/udev/vol_id not available.")
739
740
741 def mkdir(directory):
742     """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
743
744     # just silently pass as it's just fine it the directory exists
745     if not os.path.isdir(directory):
746         try:
747             os.makedirs(directory)
748         # pylint: disable-msg=W0704
749         except OSError:
750             pass
751
752
753 def copy_system_files(grml_flavour, iso_mount, target):
754     """TODO"""
755
756     squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
757     if squashfs is None:
758         logging.critical("Fatal: squashfs file not found")
759     else:
760         squashfs_target = target + '/live/'
761         execute(mkdir, squashfs_target)
762         # use install(1) for now to make sure we can write the files afterwards as normal user as well
763         logging.debug("cp %s %s" % (squashfs, target + '/live/' + grml_flavour + '.squashfs'))
764         proc = subprocess.Popen(["install", "--mode=664", squashfs, squashfs_target + grml_flavour + ".squashfs"])
765         proc.wait()
766
767     filesystem_module = search_file('filesystem.module', iso_mount)
768     if filesystem_module is None:
769         logging.critical("Fatal: filesystem.module not found")
770     else:
771         logging.debug("cp %s %s" % (filesystem_module, squashfs_target + grml_flavour + '.module'))
772         proc = subprocess.Popen(["install", "--mode=664", filesystem_module,
773                                 squashfs_target + grml_flavour + '.module'])
774         proc.wait()
775
776     release_target = target + '/boot/release/' + grml_flavour
777     execute(mkdir, release_target)
778
779     kernel = search_file('linux26', iso_mount)
780     if kernel is None:
781         logging.critical("Fatal kernel not found")
782     else:
783         logging.debug("cp %s %s" % (kernel, release_target + '/linux26'))
784         proc = subprocess.Popen(["install", "--mode=664", kernel, release_target + '/linux26'])
785         proc.wait()
786
787     initrd = search_file('initrd.gz', iso_mount)
788     if initrd is None:
789         logging.critical("Fatal: initrd not found")
790     else:
791         logging.debug("cp %s %s" % (initrd, release_target + '/initrd.gz'))
792         proc = subprocess.Popen(["install", "--mode=664", initrd, release_target + '/initrd.gz'])
793         proc.wait()
794
795
796 def copy_grml_files(iso_mount, target):
797     """TODO"""
798
799     grml_target = target + '/grml/'
800     execute(mkdir, grml_target)
801
802     for myfile in 'grml-cheatcodes.txt', 'grml-version', 'LICENSE.txt', 'md5sums', 'README.txt':
803         grml_file = search_file(myfile, iso_mount)
804         if grml_file is None:
805             logging.warn("Warning: myfile %s could not be found - can not install it", myfile)
806         else:
807             logging.debug("cp %s %s" % (grml_file, grml_target + grml_file))
808             proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_target + myfile])
809             proc.wait()
810
811     grml_web_target = grml_target + '/web/'
812     execute(mkdir, grml_web_target)
813
814     for myfile in 'index.html', 'style.css':
815         grml_file = search_file(myfile, iso_mount)
816         if grml_file is None:
817             logging.warn("Warning: myfile %s could not be found - can not install it")
818         else:
819             logging.debug("cp %s %s" % (grml_file, grml_web_target + grml_file))
820             proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_web_target + myfile])
821             proc.wait()
822
823     grml_webimg_target = grml_web_target + '/images/'
824     execute(mkdir, grml_webimg_target)
825
826     for myfile in 'button.png', 'favicon.png', 'linux.jpg', 'logo.png':
827         grml_file = search_file(myfile, iso_mount)
828         if grml_file is None:
829             logging.warn("Warning: myfile %s could not be found - can not install it")
830         else:
831             logging.debug("cp %s %s" % (grml_file, grml_webimg_target + grml_file))
832             proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_webimg_target + myfile])
833             proc.wait()
834
835
836 def copy_addons(iso_mount, target):
837     """TODO"""
838     addons = target + '/boot/addons/'
839     execute(mkdir, addons)
840
841     # grub all-in-one image
842     allinoneimg = search_file('allinone.img', iso_mount)
843     if allinoneimg is None:
844         logging.warn("Warning: allinone.img not found - can not install it")
845     else:
846         logging.debug("cp %s %s" % (allinoneimg, addons + '/allinone.img'))
847         proc = subprocess.Popen(["install", "--mode=664", allinoneimg, addons + 'allinone.img'])
848         proc.wait()
849
850     # freedos image
851     balderimg = search_file('balder10.imz', iso_mount)
852     if balderimg is None:
853         logging.warn("Warning: balder10.imz not found - can not install it")
854     else:
855         logging.debug("cp %s %s" % (balderimg, addons + '/balder10.imz'))
856         proc = subprocess.Popen(["install", "--mode=664", balderimg, addons + 'balder10.imz'])
857         proc.wait()
858
859     # memdisk image
860     memdiskimg = search_file('memdisk', iso_mount)
861     if memdiskimg is None:
862         logging.warn("Warning: memdisk not found - can not install it")
863     else:
864         logging.debug("cp %s %s" % (memdiskimg, addons + '/memdisk'))
865         proc = subprocess.Popen(["install", "--mode=664", memdiskimg, addons + 'memdisk'])
866         proc.wait()
867
868     # memtest86+ image
869     memtestimg = search_file('memtest', iso_mount)
870     if memtestimg is None:
871         logging.warn("Warning: memtest not found - can not install it")
872     else:
873         logging.debug("cp %s %s" % (memtestimg, addons + '/memtest'))
874         proc = subprocess.Popen(["install", "--mode=664", memtestimg, addons + 'memtest'])
875         proc.wait()
876
877
878 def copy_bootloader_files(iso_mount, target):
879     """"TODO"""
880
881     syslinux_target = target + '/boot/syslinux/'
882     execute(mkdir, syslinux_target)
883
884     logo = search_file('logo.16', iso_mount)
885     logging.debug("cp %s %s" % (logo, syslinux_target + 'logo.16'))
886     proc = subprocess.Popen(["install", "--mode=664", logo, syslinux_target + 'logo.16'])
887     proc.wait()
888
889     for ffile in 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10':
890         bootsplash = search_file(ffile, iso_mount)
891         logging.debug("cp %s %s" % (bootsplash, syslinux_target + ffile))
892         proc = subprocess.Popen(["install", "--mode=664", bootsplash, syslinux_target + ffile])
893         proc.wait()
894
895     grub_target = target + '/boot/grub/'
896     execute(mkdir, grub_target)
897
898     if not os.path.isfile("/usr/share/grml2usb/grub/splash.xpm.gz"):
899         logging.critical("Error: /usr/share/grml2usb/grub/splash.xpm.gz can not be read.")
900         raise
901     else:
902         logging.debug("cp /usr/share/grml2usb/grub/splash.xpm.gz %s" % grub_target + 'splash.xpm.gz')
903         proc = subprocess.Popen(["install", "--mode=664", '/usr/share/grml2usb/grub/splash.xpm.gz',
904                                 grub_target + 'splash.xpm.gz'])
905         proc.wait()
906
907     if not os.path.isfile("/usr/share/grml2usb/grub/stage2_eltorito"):
908         logging.critical("Error: /usr/share/grml2usb/grub/stage2_eltorito can not be read.")
909         raise
910     else:
911         logging.debug("cp /usr/share/grml2usb/grub/stage2_eltorito to %s" % grub_target + 'stage2_eltorito')
912         proc = subprocess.Popen(["install", "--mode=664", '/usr/share/grml2usb/grub/stage2_eltorito',
913                                 grub_target + 'stage2_eltorito'])
914         proc.wait()
915
916
917 def install_iso_files(grml_flavour, iso_mount, device, target):
918     """Copy files from ISO on given target"""
919
920     # TODO
921     # * make sure grml_flavour, iso_mount, target are set when the function is called, otherwise raise exception
922     # * provide alternative search_file() if file information is stored in a config.ini file?
923     # * catch "install: .. No space left on device" & CO
924     # * abstract copy logic to make the code shorter and get rid of spaghettis ;)
925
926     if options.dryrun:
927         logging.info("Would copy files to %s", iso_mount)
928         return 0
929     elif not options.bootloaderonly:
930         logging.info("Copying files. This might take a while....")
931         copy_system_files(grml_flavour, iso_mount, target)
932         copy_grml_files(iso_mount, target)
933
934     if not options.skipaddons:
935         copy_addons(iso_mount, target)
936
937     if not options.copyonly:
938         copy_bootloader_files(iso_mount, target)
939
940         if not options.dryrun:
941             handle_bootloader_config(grml_flavour, device, target) # FIXME
942
943     # make sure we sync filesystems before returning
944     proc = subprocess.Popen(["sync"])
945     proc.wait()
946
947
948 def uninstall_files(device):
949     """Get rid of all grml files on specified device
950
951     @device: partition where grml2usb files should be removed from"""
952
953     # TODO
954     logging.critical("TODO: uninstalling files from %s not yet implement, sorry." % device)
955
956
957 def identify_grml_flavour(mountpath):
958     """Get name of grml flavour
959
960     @mountpath: path where the grml ISO is mounted to
961     @return: name of grml-flavour"""
962
963     version_file = search_file('grml-version', mountpath)
964
965     if version_file == "":
966         logging.critical("Error: could not find grml-version file.")
967         raise
968
969     try:
970         tmpfile = open(version_file, 'r')
971         grml_info = tmpfile.readline()
972         grml_flavour = re.match(r'[\w-]*', grml_info).group()
973     except TypeError:
974         raise
975     except:
976         logging.critical("Unexpected error:", sys.exc_info()[0])
977         raise
978
979     return grml_flavour
980
981
982 def handle_bootloader_config(grml_flavour, device, target):
983     """TODO"""
984
985     logging.debug("Generating grub configuration")
986     #with open("...", "w") as f:
987     #f.write("bla bla bal")
988
989     grub_target = target + '/boot/grub/'
990     # should be present via copy_bootloader_files(), but make sure it exists:
991     execute(mkdir, grub_target)
992     # we have to adjust root() inside grub configuration
993     if device[-1:].isdigit():
994         install_partition = device[-1:]
995
996     # grub1 config
997     logging.debug("Creating grub1 configuration file")
998     grub_config_file = open(grub_target + 'menu.lst', 'w')
999     grub_config_file.write(generate_grub1_config(grml_flavour, install_partition, options.bootoptions))
1000     grub_config_file.close()
1001
1002     # TODO => generate_main_grub1_config() && generate_flavour_specific_grub1_config()
1003
1004     # grub2 config
1005     grub2_cfg = grub_target + 'grub.cfg'
1006     logging.debug("Creating grub2 configuration file")
1007
1008     # install main configuration only *once*, no matter how many ISOs we have:
1009     if os.path.isfile(grub2_cfg):
1010         string = open(grub2_cfg).readline()
1011         main_identifier = re.compile(".*main config generated at: %s.*" % re.escape(str(DATESTAMP)))
1012         if not re.match(main_identifier, string):
1013             grub2_config_file = open(grub2_cfg, 'w')
1014             logging.info("Notice: grml flavour %s is being installed as the default booting system." % grml_flavour)
1015             grub2_config_file.write(generate_main_grub2_config(grml_flavour, install_partition, options.bootoptions))
1016             grub2_config_file.close()
1017     else:
1018         grub2_config_file = open(grub2_cfg, 'w')
1019         grub2_config_file.write(generate_main_grub2_config(grml_flavour, install_partition, options.bootoptions))
1020         grub2_config_file.close()
1021
1022     grub_flavour_config = True
1023     if os.path.isfile(grub2_cfg):
1024         string = open(grub2_cfg).readlines()
1025         logging.info("Notice: you can boot flavour %s using '%s' on the commandline." % (grml_flavour, grml_flavour))
1026         flavour = re.compile("grml2usb for %s: %s" % (re.escape(grml_flavour), re.escape(str(DATESTAMP))))
1027         for line in string:
1028             if flavour.match(line):
1029                 grub_flavour_config = False
1030
1031     if grub_flavour_config:
1032         grub2_config_file = open(grub2_cfg, 'a')
1033         grub2_config_file.write(generate_flavour_specific_grub2_config(grml_flavour, install_partition, options.bootoptions))
1034         grub2_config_file.close( )
1035
1036
1037     logging.info("Generating syslinux configuration")
1038     syslinux_target = target + '/boot/syslinux/'
1039     # should be present via  copy_bootloader_files(), but make sure it exits:
1040     execute(mkdir, syslinux_target)
1041     syslinux_cfg = syslinux_target + 'syslinux.cfg'
1042
1043     # install main configuration only *once*, no matter how many ISOs we have:
1044     if os.path.isfile(syslinux_cfg):
1045         string = open(syslinux_cfg).readline()
1046         main_identifier = re.compile(".*main config generated at: %s.*" % re.escape(str(DATESTAMP)))
1047         if not re.match(main_identifier, string):
1048             syslinux_config_file = open(syslinux_cfg, 'w')
1049             logging.info("Notice: grml flavour %s is being installed as the default booting system." % grml_flavour)
1050             syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, options.bootoptions))
1051             syslinux_config_file.close()
1052     else:
1053         syslinux_config_file = open(syslinux_cfg, 'w')
1054         syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, options.bootoptions))
1055         syslinux_config_file.close()
1056
1057     # install flavour specific configuration only *once* as well
1058     # kind of ugly - I'm pretty sure this could be smoother...
1059     syslinux_flavour_config = True
1060     if os.path.isfile(syslinux_cfg):
1061         string = open(syslinux_cfg).readlines()
1062         logging.info("Notice: you can boot flavour %s using '%s' on the commandline." % (grml_flavour, grml_flavour))
1063         flavour = re.compile("grml2usb for %s: %s" % (re.escape(grml_flavour), re.escape(str(DATESTAMP))))
1064         for line in string:
1065             if flavour.match(line):
1066                 syslinux_flavour_config = False
1067
1068     if syslinux_flavour_config:
1069         syslinux_config_file = open(syslinux_cfg, 'a')
1070         syslinux_config_file.write(generate_flavour_specific_syslinux_config(grml_flavour, options.bootoptions))
1071         syslinux_config_file.close( )
1072
1073     logging.debug("Generating isolinux/syslinux splash %s" % syslinux_target + 'boot.msg')
1074     isolinux_splash = open(syslinux_target + 'boot.msg', 'w')
1075     isolinux_splash.write(generate_isolinux_splash(grml_flavour))
1076     isolinux_splash.close( )
1077
1078
1079 def handle_iso(iso, device):
1080     """Main logic for mounting ISOs and copying files.
1081
1082     @iso: full path to the ISO that should be installed to the specified device
1083     @device: partition where the specified ISO should be installed to"""
1084
1085     logging.info("Using ISO %s" % iso)
1086
1087     if os.path.isdir(iso):
1088         logging.critical("TODO: /live/image handling not yet implemented - sorry") # TODO
1089         sys.exit(1)
1090
1091     iso_mountpoint = tempfile.mkdtemp()
1092     register_tmpfile(iso_mountpoint)
1093     remove_iso_mountpoint = True
1094
1095     if not os.path.isfile(iso):
1096         logging.critical("Fatal: specified ISO %s could not be read" % iso)
1097         cleanup()
1098         sys.exit(1)
1099
1100     try:
1101         mount(iso, iso_mountpoint, ["-o", "loop", "-t", "iso9660"])
1102     except CriticalException, error:
1103         logging.critical("Fatal: %s" % error)
1104         sys.exit(1)
1105
1106     if os.path.isdir(device):
1107         logging.info("Specified target is a directory, not mounting therefor.")
1108         device_mountpoint = device
1109         remove_device_mountpoint = False
1110         # skip_mbr = True
1111     else:
1112         device_mountpoint = tempfile.mkdtemp()
1113         register_tmpfile(device_mountpoint)
1114         remove_device_mountpoint = True
1115         try:
1116             mount(device, device_mountpoint, "")
1117         except CriticalException, error:
1118             logging.critical("Fatal: %s" % error)
1119             cleanup()
1120             sys.exit(1)
1121
1122     try:
1123         grml_flavour = identify_grml_flavour(iso_mountpoint)
1124         logging.info("Identified grml flavour \"%s\"." % grml_flavour)
1125         install_iso_files(grml_flavour, iso_mountpoint, device, device_mountpoint)
1126     except TypeError:
1127         logging.critical("Fatal: a critical error happend during execution (not a grml ISO?), giving up")
1128         sys.exit(1)
1129     finally:
1130         if os.path.isdir(iso_mountpoint) and remove_iso_mountpoint:
1131             unmount(iso_mountpoint, "")
1132             os.rmdir(iso_mountpoint)
1133             unregister_tmpfile(iso_mountpoint)
1134         if remove_device_mountpoint:
1135             unmount(device_mountpoint, "")
1136             if os.path.isdir(device_mountpoint):
1137                 os.rmdir(device_mountpoint)
1138                 unregister_tmpfile(device_mountpoint)
1139
1140
1141 def handle_mbr(device):
1142     """TODO"""
1143
1144     # install MBR
1145     # if not options.mbr:
1146     #     logging.info("You are NOT using the --mbr option. Consider using it if your device does not boot.")
1147     # else:
1148     # make sure we install MBR on /dev/sdX and not /dev/sdX#
1149
1150     # make sure we have syslinux available
1151     # if options.mbr:
1152     if not options.skipmbr:
1153         if not which("syslinux") and not options.copyonly and not options.dryrun:
1154             logging.critical('Sorry, syslinux not available. Exiting.')
1155             logging.critical('Please install syslinux or consider using the --grub option.')
1156             sys.exit(1)
1157
1158     if not options.skipmbr:
1159         if device[-1:].isdigit():
1160             mbr_device = re.match(r'(.*?)\d*$', device).group(1)
1161
1162         try:
1163             install_mbr(mbr_device)
1164         except IOError, error:
1165             logging.critical("Execution failed: %s", error)
1166             sys.exit(1)
1167         except Exception, error:
1168             logging.critical("Execution failed: %s", error)
1169             sys.exit(1)
1170
1171
1172 def handle_vfat(device):
1173     """TODO"""
1174
1175     # make sure we have mkfs.vfat available
1176     if options.fat16 and not options.force:
1177         if not which("mkfs.vfat") and not options.copyonly and not options.dryrun:
1178             logging.critical('Sorry, mkfs.vfat not available. Exiting.')
1179             logging.critical('Please make sure to install dosfstools.')
1180             sys.exit(1)
1181
1182         # make sure the user is aware of what he is doing
1183         f = raw_input("Are you sure you want to format the device with a fat16 filesystem? y/N ")
1184         if f == "y" or f == "Y":
1185             logging.info("Note: you can skip this question using the option --force")
1186             mkfs_fat16(device)
1187         else:
1188             sys.exit(1)
1189
1190     # check for vfat filesystem
1191     if device is not None and not os.path.isdir(device):
1192         try:
1193             check_for_fat(device)
1194         except CriticalException, error:
1195             logging.critical("Execution failed: %s", error)
1196             sys.exit(1)
1197
1198     if not check_for_usbdevice(device):
1199         print "Warning: the specified device %s does not look like a removable usb device." % device
1200         f = raw_input("Do you really want to continue? y/N ")
1201         if f == "y" or f == "Y":
1202             pass
1203         else:
1204             sys.exit(1)
1205
1206
1207 def handle_compat_warning(device):
1208     """TODO"""
1209
1210     # make sure we can replace old grml2usb script and warn user when using old way of life:
1211     if device.startswith("/mnt/external") or device.startswith("/mnt/usb") and not options.force:
1212         print "Warning: the semantics of grml2usb has changed."
1213         print "Instead of using grml2usb /path/to/iso %s you might" % device
1214         print "want to use grml2usb /path/to/iso /dev/... instead."
1215         print "Please check out the grml2usb manpage for details."
1216         f = raw_input("Do you really want to continue? y/N ")
1217         if f == "y" or f == "Y":
1218             pass
1219         else:
1220             sys.exit(1)
1221
1222
1223 def handle_logging():
1224     """TODO"""
1225
1226     if options.verbose:
1227         FORMAT = "%(asctime)-15s %(message)s"
1228         logging.basicConfig(level=logging.DEBUG, format=FORMAT)
1229     elif options.quiet:
1230         FORMAT = "Critial: %(message)s"
1231         logging.basicConfig(level=logging.CRITICAL, format=FORMAT)
1232     else:
1233         FORMAT = "Info: %(message)s"
1234         logging.basicConfig(level=logging.INFO, format=FORMAT)
1235
1236
1237 def handle_bootloader(device):
1238     """TODO"""
1239     # Install bootloader only if not using the --copy-only option
1240     if options.copyonly:
1241         logging.info("Not installing bootloader and its files as requested via option copyonly.")
1242     else:
1243         install_bootloader(device)
1244
1245
1246 def main():
1247     """Main function [make pylint happy :)]"""
1248
1249     if options.version:
1250         print os.path.basename(sys.argv[0]) + " " + PROG_VERSION
1251         sys.exit(0)
1252
1253     if len(args) < 2:
1254         parser.error("invalid usage")
1255
1256     # log handling
1257     handle_logging()
1258
1259     # make sure we have the appropriate permissions
1260     check_uid_root()
1261
1262     if options.dryrun:
1263         logging.info("Running in simulate mode as requested via option dry-run.")
1264
1265     # specified arguments
1266     device = args[len(args) - 1]
1267     isos = args[0:len(args) - 1]
1268
1269     # provide upgrade path
1270     handle_compat_warning(device)
1271
1272     # check for vfat partition
1273     handle_vfat(device)
1274
1275     # main operation (like installing files)
1276     for iso in isos:
1277         handle_iso(iso, device)
1278
1279     # install mbr
1280     handle_mbr(device)
1281
1282     handle_bootloader(device)
1283
1284     # finally be politely :)
1285     logging.info("Finished execution of grml2usb (%s). Have fun with your grml system." % PROG_VERSION)
1286
1287
1288 if __name__ == "__main__":
1289     try:
1290         main()
1291     except KeyboardInterrupt:
1292         logging.info("Received KeyboardInterrupt")
1293         cleanup()
1294
1295 ## END OF FILE #################################################################
1296 # vim:foldmethod=indent expandtab ai ft=python tw=120 fileencoding=utf-8