0ea1d019b5469490fd59c1211eb06489d25d9b37
[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 [TODO]")
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_grub_config(grml_flavour):
217     """Generate grub configuration for use via menu.lst
218
219     @grml_flavour: name of grml flavour the configuration should be generated for"""
220     # TODO
221     # * what about systems using grub2 without having grub1 available?
222     # * support grub2?
223
224     return("""\
225 # misc options:
226 timeout 30
227 # color red/blue green/black
228 splashimage=/boot/grub/splash.xpm.gz
229 foreground  = 000000
230 background  = FFCC33
231
232 # define entries:
233 title %(grml_flavour)s  - Default boot (using 1024x768 framebuffer)
234 kernel /boot/release/%(grml_flavour)s/linux26 apm=power-off lang=us vga=791 quiet boot=live nomce module=%(grml_flavour)s
235 initrd /boot/release/%(grml_flavour)s/initrd.gz
236
237 # TODO: extend configuration :)
238 """ % {'grml_flavour': grml_flavour} )
239
240
241 def generate_isolinux_splash(grml_flavour):
242     """Generate bootsplash for isolinux/syslinux
243
244     @grml_flavour: name of grml flavour the configuration should be generated for"""
245
246     # TODO: adjust last bootsplash line (the one following the "Some information and boot ...")
247
248     grml_name = grml_flavour
249
250     return("""\
251 \ f17\f\18/boot/syslinux/logo.16
252
253 Some information and boot options available via keys F2 - F10. http://grml.org/
254 %(grml_name)s
255 """ % {'grml_name': grml_name} )
256
257
258 def generate_main_syslinux_config(grml_flavour, bootoptions):
259     """Generate main configuration for use in syslinux.cfg
260
261     @grml_flavour: name of grml flavour the configuration should be generated for
262     @bootoptions: bootoptions that should be used as a default"""
263
264     local_datestamp = DATESTAMP
265
266     return("""\
267 ## main syslinux configuration - generated by grml2usb [main config generated at: %(local_datestamp)s]
268 # use this to control the bootup via a serial port
269 # SERIAL 0 9600
270 DEFAULT grml
271 TIMEOUT 300
272 PROMPT 1
273 DISPLAY /boot/syslinux/boot.msg
274 F1 /boot/syslinux/boot.msg
275 F2 /boot/syslinux/f2
276 F3 /boot/syslinux/f3
277 F4 /boot/syslinux/f4
278 F5 /boot/syslinux/f5
279 F6 /boot/syslinux/f6
280 F7 /boot/syslinux/f7
281 F8 /boot/syslinux/f8
282 F9 /boot/syslinux/f9
283 F10 /boot/syslinux/f10
284 ## end of main configuration
285
286 ## global configuration
287 # the default option (using %(grml_flavour)s)
288 LABEL  grml
289 KERNEL /boot/release/%(grml_flavour)s/linux26
290 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s %(bootoptions)s
291
292 # memtest
293 LABEL  memtest
294 KERNEL /boot/addons/memtest
295
296 # grub
297 LABEL grub
298 MENU LABEL grub
299 KERNEL /boot/addons/memdisk
300 APPEND initrd=/boot/addons/allinone.img
301
302 # dos
303 LABEL dos
304 MENU LABEL dos
305 KERNEL /boot/addons/memdisk
306 APPEND initrd=/boot/addons/balder10.imz
307
308 ## end of global configuration
309 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
310
311
312 def generate_flavour_specific_syslinux_config(grml_flavour, bootoptions):
313     """Generate flavour specific configuration for use in syslinux.cfg
314
315     @grml_flavour: name of grml flavour the configuration should be generated for
316     @bootoptions: bootoptions that should be used as a default"""
317
318     local_datestamp = DATESTAMP
319
320     return("""\
321
322 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
323 LABEL  %(grml_flavour)s
324 KERNEL /boot/release/%(grml_flavour)s/linux26
325 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s %(bootoptions)s
326
327 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
328 LABEL  %(grml_flavour)s2ram
329 KERNEL /boot/release/%(grml_flavour)s/linux26
330 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
331
332 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
333 LABEL  %(grml_flavour)s-debug
334 KERNEL /boot/release/%(grml_flavour)s/linux26
335 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
336
337 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
338 LABEL  %(grml_flavour)s-x
339 KERNEL /boot/release/%(grml_flavour)s/linux26
340 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
341
342 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
343 LABEL  %(grml_flavour)s-nofb
344 KERNEL /boot/release/%(grml_flavour)s/linux26
345 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
346
347 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
348 LABEL  %(grml_flavour)s-failsafe
349 KERNEL /boot/release/%(grml_flavour)s/linux26
350 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
351
352 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
353 LABEL  %(grml_flavour)s-forensic
354 KERNEL /boot/release/%(grml_flavour)s/linux26
355 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
356
357 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
358 LABEL  %(grml_flavour)s-serial
359 KERNEL /boot/release/%(grml_flavour)s/linux26
360 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
361 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
362
363
364 def install_grub(device):
365     """Install grub on specified device.
366
367     @device: partition where grub should be installed to"""
368
369     if options.dryrun:
370         logging.info("Would execute grub-install %s now.", device)
371     else:
372         logging.critical("TODO: sorry - grub-install %s not implemented yet"  % device)
373
374
375 def install_syslinux(device):
376     """Install syslinux on specified device.
377
378     @device: partition where syslinux should be installed to"""
379
380     if options.dryrun:
381         logging.info("Would install syslinux as bootloader on %s", device)
382         return 0
383
384     # syslinux -d boot/isolinux /dev/sdb1
385     logging.info("Installing syslinux as bootloader")
386     logging.debug("syslinux -d boot/syslinux %s" % device)
387     proc = subprocess.Popen(["syslinux", "-d", "boot/syslinux", device])
388     proc.wait()
389     if proc.returncode != 0:
390         raise Exception("error executing syslinux")
391
392
393 def install_bootloader(device):
394     """Install bootloader on specified device.
395
396     @device: partition where bootloader should be installed to"""
397
398     # Install bootloader on the device (/dev/sda),
399     # not on the partition itself (/dev/sda1)?
400     #if partition[-1:].isdigit():
401     #    device = re.match(r'(.*?)\d*$', partition).group(1)
402     #else:
403     #    device = partition
404
405     if options.grub:
406         install_grub(device)
407     else:
408         install_syslinux(device)
409
410
411 def install_lilo_mbr(lilo, device):
412     """TODO"""
413
414     # TODO: check out the *real* difference between:
415     # * mbr-install /dev/ice
416     # * lilo -S /dev/null -M /dev/ice ext && lilo -S /dev/null -A /dev/ice 1
417     # * cat /usr/lib/syslinux/mbr.bin > /dev/ice
418     # * syslinux -sf /dev/iceX
419     # * ...?
420
421     # to support -A for extended partitions:
422     logging.info("Installing MBR")
423     logging.debug("%s -S /dev/null -M %s ext" % (lilo, device))
424     proc = subprocess.Popen([lilo, "-S", "/dev/null", "-M", device, "ext"])
425     proc.wait()
426     if proc.returncode != 0:
427         raise Exception("error executing lilo")
428
429     # activate partition:
430     logging.debug("%s -S /dev/null -A %s 1" % (lilo, device))
431     proc = subprocess.Popen([lilo, "-S", "/dev/null", "-A", device, "1"])
432     proc.wait()
433     if proc.returncode != 0:
434         raise Exception("error executing lilo")
435
436
437 def install_syslinux_mbr(device):
438     """TODO"""
439
440     # lilo's mbr is broken, use the one from syslinux instead:
441     if not os.path.isfile("/usr/lib/syslinux/mbr.bin"):
442         raise Exception("/usr/lib/syslinux/mbr.bin can not be read")
443
444     logging.debug("cat /usr/lib/syslinux/mbr.bin > %s" % device)
445     try:
446         # TODO -> use Popen instead?
447         retcode = subprocess.call("cat /usr/lib/syslinux/mbr.bin > "+ device, shell=True)
448         if retcode < 0:
449             logging.critical("Error copying MBR to device (%s)" % retcode)
450     except OSError, error:
451         logging.critical("Execution failed:", error)
452
453
454 def install_mbr(device):
455     """Install a default master boot record on given device
456
457     @device: device where MBR should be installed to"""
458
459     if not is_writeable(device):
460         raise IOError("device not writeable for user")
461
462     # try to use system's lilo
463     if which("lilo"):
464         lilo = which("lilo")
465     else:
466         # otherwise fall back to our static version
467         from platform import architecture
468         if architecture()[0] == '64bit':
469             lilo = '/usr/share/grml2usb/lilo/lilo.static.amd64'
470         else:
471             lilo = '/usr/share/grml2usb/lilo/lilo.static.i386'
472     # finally prefer a specified lilo executable
473     if options.lilo:
474         lilo = options.lilo
475
476     if not is_exe(lilo):
477         raise Exception("lilo executable can not be execute")
478
479     if options.dryrun:
480         logging.info("Would install MBR running lilo and using syslinux.")
481         return 0
482
483     install_lilo_mbr(lilo, device)
484     install_syslinux_mbr(device)
485
486
487 def is_writeable(device):
488     """Check if the device is writeable for the current user
489
490     @device: partition where bootloader should be installed to"""
491
492     if not device:
493         return False
494         #raise Exception("no device for checking write permissions")
495
496     if not os.path.exists(device):
497         return False
498
499     return os.access(device, os.W_OK) and os.access(device, os.R_OK)
500
501
502 def mount(source, target, mount_options):
503     """Mount specified source on given target
504
505     @source: name of device/ISO that should be mounted
506     @target: directory where the ISO should be mounted to
507     @options: mount specific options"""
508
509     # notice: options.dryrun does not work here, as we have to
510     # locate files and identify the grml flavour
511     logging.debug("mount %s %s %s" % (mount_options, source, target))
512     proc = subprocess.Popen(["mount"] + list(mount_options) + [source, target])
513     proc.wait()
514     if proc.returncode != 0:
515         raise CriticalException("Error executing mount")
516     else:
517         logging.debug("register_mountpoint(%s)" % target)
518         register_mountpoint(target)
519
520
521 def unmount(target, unmount_options):
522     """Unmount specified target
523
524     @target: target where something is mounted on and which should be unmounted
525     @options: options for umount command"""
526
527     # make sure we unmount only already mounted targets
528     target_unmount = False
529     mounts = open('/proc/mounts').readlines()
530     mountstring = re.compile(".*%s.*" % re.escape(target))
531     for line in mounts:
532         if re.match(mountstring, line):
533             target_unmount = True
534
535     if not target_unmount:
536         logging.debug("%s not mounted anymore" % target)
537     else:
538         logging.debug("umount %s %s" % (list(unmount_options), target))
539         proc = subprocess.Popen(["umount"] + list(unmount_options) + [target])
540         proc.wait()
541         if proc.returncode != 0:
542             raise Exception("Error executing umount")
543         else:
544             logging.debug("unregister_mountpoint(%s)" % target)
545             unregister_mountpoint(target)
546
547
548 def check_for_usbdevice(device):
549     """Check whether the specified device is a removable USB device
550
551     @device: device name, like /dev/sda1 or /dev/sda
552     """
553
554     usbdevice = re.match(r'/dev/(.*?)\d*$', device).group(1)
555     usbdevice = os.path.realpath('/sys/class/block/' + usbdevice + '/removable')
556     if os.path.isfile(usbdevice):
557         is_usb = open(usbdevice).readline()
558         if is_usb == "1":
559             return 0
560         else:
561             return 1
562
563
564 def check_for_fat(partition):
565     """Check whether specified partition is a valid VFAT/FAT16 filesystem
566
567     @partition: device name of partition"""
568
569     try:
570         udev_info = subprocess.Popen(["/lib/udev/vol_id", "-t", partition],
571                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
572         filesystem = udev_info.communicate()[0].rstrip()
573
574         if udev_info.returncode == 2:
575             raise CriticalException("Failed to read device %s"
576                                     "(wrong UID/permissions or device not present?)" % partition)
577
578         if filesystem != "vfat":
579             raise CriticalException("Device %s does not contain a FAT16 partition." % partition)
580
581     except OSError:
582         raise CriticalException("Sorry, /lib/udev/vol_id not available.")
583
584
585 def mkdir(directory):
586     """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
587
588     # just silently pass as it's just fine it the directory exists
589     if not os.path.isdir(directory):
590         try:
591             os.makedirs(directory)
592         # pylint: disable-msg=W0704
593         except OSError:
594             pass
595
596
597 def copy_system_files(grml_flavour, iso_mount, target):
598     """TODO"""
599
600     squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
601     if squashfs is None:
602         logging.critical("Fatal: squashfs file not found")
603     else:
604         squashfs_target = target + '/live/'
605         execute(mkdir, squashfs_target)
606         # use install(1) for now to make sure we can write the files afterwards as normal user as well
607         logging.debug("cp %s %s" % (squashfs, target + '/live/' + grml_flavour + '.squashfs'))
608         proc = subprocess.Popen(["install", "--mode=664", squashfs, squashfs_target + grml_flavour + ".squashfs"])
609         proc.wait()
610
611     filesystem_module = search_file('filesystem.module', iso_mount)
612     if filesystem_module is None:
613         logging.critical("Fatal: filesystem.module not found")
614     else:
615         logging.debug("cp %s %s" % (filesystem_module, squashfs_target + grml_flavour + '.module'))
616         proc = subprocess.Popen(["install", "--mode=664", filesystem_module,
617                                 squashfs_target + grml_flavour + '.module'])
618         proc.wait()
619
620     release_target = target + '/boot/release/' + grml_flavour
621     execute(mkdir, release_target)
622
623     kernel = search_file('linux26', iso_mount)
624     if kernel is None:
625         logging.critical("Fatal kernel not found")
626     else:
627         logging.debug("cp %s %s" % (kernel, release_target + '/linux26'))
628         proc = subprocess.Popen(["install", "--mode=664", kernel, release_target + '/linux26'])
629         proc.wait()
630
631     initrd = search_file('initrd.gz', iso_mount)
632     if initrd is None:
633         logging.critical("Fatal: initrd not found")
634     else:
635         logging.debug("cp %s %s" % (initrd, release_target + '/initrd.gz'))
636         proc = subprocess.Popen(["install", "--mode=664", initrd, release_target + '/initrd.gz'])
637         proc.wait()
638
639
640 def copy_grml_files(iso_mount, target):
641     """TODO"""
642
643     grml_target = target + '/grml/'
644     execute(mkdir, grml_target)
645
646     for myfile in 'grml-cheatcodes.txt', 'grml-version', 'LICENSE.txt', 'md5sums', 'README.txt':
647         grml_file = search_file(myfile, iso_mount)
648         if grml_file is None:
649             logging.warn("Warning: myfile %s could not be found - can not install it", myfile)
650         else:
651             logging.debug("cp %s %s" % (grml_file, grml_target + grml_file))
652             proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_target + myfile])
653             proc.wait()
654
655     grml_web_target = grml_target + '/web/'
656     execute(mkdir, grml_web_target)
657
658     for myfile in 'index.html', 'style.css':
659         grml_file = search_file(myfile, iso_mount)
660         if grml_file is None:
661             logging.warn("Warning: myfile %s could not be found - can not install it")
662         else:
663             logging.debug("cp %s %s" % (grml_file, grml_web_target + grml_file))
664             proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_web_target + myfile])
665             proc.wait()
666
667     grml_webimg_target = grml_web_target + '/images/'
668     execute(mkdir, grml_webimg_target)
669
670     for myfile in 'button.png', 'favicon.png', 'linux.jpg', 'logo.png':
671         grml_file = search_file(myfile, iso_mount)
672         if grml_file is None:
673             logging.warn("Warning: myfile %s could not be found - can not install it")
674         else:
675             logging.debug("cp %s %s" % (grml_file, grml_webimg_target + grml_file))
676             proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_webimg_target + myfile])
677             proc.wait()
678
679
680 def copy_addons(iso_mount, target):
681     """TODO"""
682     addons = target + '/boot/addons/'
683     execute(mkdir, addons)
684
685     # grub all-in-one image
686     allinoneimg = search_file('allinone.img', iso_mount)
687     if allinoneimg is None:
688         logging.warn("Warning: allinone.img not found - can not install it")
689     else:
690         logging.debug("cp %s %s" % (allinoneimg, addons + '/allinone.img'))
691         proc = subprocess.Popen(["install", "--mode=664", allinoneimg, addons + 'allinone.img'])
692         proc.wait()
693
694     # freedos image
695     balderimg = search_file('balder10.imz', iso_mount)
696     if balderimg is None:
697         logging.warn("Warning: balder10.imz not found - can not install it")
698     else:
699         logging.debug("cp %s %s" % (balderimg, addons + '/balder10.imz'))
700         proc = subprocess.Popen(["install", "--mode=664", balderimg, addons + 'balder10.imz'])
701         proc.wait()
702
703     # memdisk image
704     memdiskimg = search_file('memdisk', iso_mount)
705     if memdiskimg is None:
706         logging.warn("Warning: memdisk not found - can not install it")
707     else:
708         logging.debug("cp %s %s" % (memdiskimg, addons + '/memdisk'))
709         proc = subprocess.Popen(["install", "--mode=664", memdiskimg, addons + 'memdisk'])
710         proc.wait()
711
712     # memtest86+ image
713     memtestimg = search_file('memtest', iso_mount)
714     if memtestimg is None:
715         logging.warn("Warning: memtest not found - can not install it")
716     else:
717         logging.debug("cp %s %s" % (memtestimg, addons + '/memtest'))
718         proc = subprocess.Popen(["install", "--mode=664", memtestimg, addons + 'memtest'])
719         proc.wait()
720
721
722 def copy_bootloader_files(iso_mount, target):
723     """"TODO"""
724
725     syslinux_target = target + '/boot/syslinux/'
726     execute(mkdir, syslinux_target)
727
728     logo = search_file('logo.16', iso_mount)
729     logging.debug("cp %s %s" % (logo, syslinux_target + 'logo.16'))
730     proc = subprocess.Popen(["install", "--mode=664", logo, syslinux_target + 'logo.16'])
731     proc.wait()
732
733     for ffile in 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10':
734         bootsplash = search_file(ffile, iso_mount)
735         logging.debug("cp %s %s" % (bootsplash, syslinux_target + ffile))
736         proc = subprocess.Popen(["install", "--mode=664", bootsplash, syslinux_target + ffile])
737         proc.wait()
738
739     grub_target = target + '/boot/grub/'
740     execute(mkdir, grub_target)
741
742     if not os.path.isfile("/usr/share/grml2usb/grub/splash.xpm.gz"):
743         logging.critical("Error: /usr/share/grml2usb/grub/splash.xpm.gz can not be read.")
744         raise
745     else:
746         logging.debug("cp /usr/share/grml2usb/grub/splash.xpm.gz %s" % grub_target + 'splash.xpm.gz')
747         proc = subprocess.Popen(["install", "--mode=664", '/usr/share/grml2usb/grub/splash.xpm.gz',
748                                 grub_target + 'splash.xpm.gz'])
749         proc.wait()
750
751     if not os.path.isfile("/usr/share/grml2usb/grub/stage2_eltorito"):
752         logging.critical("Error: /usr/share/grml2usb/grub/stage2_eltorito can not be read.")
753         raise
754     else:
755         logging.debug("cp /usr/share/grml2usb/grub/stage2_eltorito to %s" % grub_target + 'stage2_eltorito')
756         proc = subprocess.Popen(["install", "--mode=664", '/usr/share/grml2usb/grub/stage2_eltorito',
757                                 grub_target + 'stage2_eltorito'])
758         proc.wait()
759
760
761 def install_iso_files(grml_flavour, iso_mount, target):
762     """Copy files from ISO on given target"""
763
764     # TODO
765     # * make sure grml_flavour, iso_mount, target are set when the function is called, otherwise raise exception
766     # * provide alternative search_file() if file information is stored in a config.ini file?
767     # * catch "install: .. No space left on device" & CO
768     # * abstract copy logic to make the code shorter and get rid of spaghettis ;)
769
770     if options.dryrun:
771         logging.info("Would copy files to %s", iso_mount)
772         return 0
773     elif not options.bootloaderonly:
774         logging.info("Copying files. This might take a while....")
775         copy_system_files(grml_flavour, iso_mount, target)
776         copy_grml_files(iso_mount, target)
777
778     if not options.skipaddons:
779         copy_addons(iso_mount, target)
780
781     if not options.copyonly:
782         copy_bootloader_files(iso_mount, target)
783
784         if not options.dryrun:
785             handle_bootloader_config(grml_flavour, target) # FIXME
786
787     # make sure we sync filesystems before returning
788     proc = subprocess.Popen(["sync"])
789     proc.wait()
790
791
792 def uninstall_files(device):
793     """Get rid of all grml files on specified device
794
795     @device: partition where grml2usb files should be removed from"""
796
797     # TODO
798     logging.critical("TODO: uninstalling files from %s not yet implement, sorry." % device)
799
800
801 def identify_grml_flavour(mountpath):
802     """Get name of grml flavour
803
804     @mountpath: path where the grml ISO is mounted to
805     @return: name of grml-flavour"""
806
807     version_file = search_file('grml-version', mountpath)
808
809     if version_file == "":
810         logging.critical("Error: could not find grml-version file.")
811         raise
812
813     try:
814         tmpfile = open(version_file, 'r')
815         grml_info = tmpfile.readline()
816         grml_flavour = re.match(r'[\w-]*', grml_info).group()
817     except TypeError:
818         raise
819     except:
820         logging.critical("Unexpected error:", sys.exc_info()[0])
821         raise
822
823     return grml_flavour
824
825
826 def handle_bootloader_config(grml_flavour, target):
827     """TODO"""
828
829     logging.debug("Generating grub configuration")
830     #with open("...", "w") as f:
831     #f.write("bla bla bal")
832
833     grub_target = target + '/boot/grub/'
834     # should be present via copy_bootloader_files(), but make sure it exists:
835     execute(mkdir, grub_target)
836     grub_config_file = open(grub_target + 'menu.lst', 'w')
837     grub_config_file.write(generate_grub_config(grml_flavour))
838     grub_config_file.close()
839
840     logging.info("Generating syslinux configuration")
841     syslinux_target = target + '/boot/syslinux/'
842     # should be present via  copy_bootloader_files(), but make sure it exits:
843     execute(mkdir, syslinux_target)
844     syslinux_cfg = syslinux_target + 'syslinux.cfg'
845
846     # install main configuration only *once*, no matter how many ISOs we have:
847     if os.path.isfile(syslinux_cfg):
848         string = open(syslinux_cfg).readline()
849         main_identifier = re.compile(".*main config generated at: %s.*" % re.escape(str(DATESTAMP)))
850         if not re.match(main_identifier, string):
851             syslinux_config_file = open(syslinux_cfg, 'w')
852             logging.info("Notice: grml flavour %s is being installed as the default booting system." % grml_flavour)
853             syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, options.bootoptions))
854             syslinux_config_file.close()
855     else:
856         syslinux_config_file = open(syslinux_cfg, 'w')
857         syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, options.bootoptions))
858         syslinux_config_file.close()
859
860     # install flavour specific configuration only *once* as well
861     # kind of ugly - I'm pretty sure this could be smoother...
862     flavour_config = True
863     if os.path.isfile(syslinux_cfg):
864         string = open(syslinux_cfg).readlines()
865         logging.info("Notice: you can boot flavour %s using '%s' on the commandline." % (grml_flavour, grml_flavour))
866         flavour = re.compile("grml2usb for %s: %s" % (re.escape(grml_flavour), re.escape(str(DATESTAMP))))
867         for line in string:
868             if flavour.match(line):
869                 flavour_config = False
870
871     if flavour_config:
872         syslinux_config_file = open(syslinux_cfg, 'a')
873         syslinux_config_file.write(generate_flavour_specific_syslinux_config(grml_flavour, options.bootoptions))
874         syslinux_config_file.close( )
875
876     logging.debug("Generating isolinux/syslinux splash %s" % syslinux_target + 'boot.msg')
877     isolinux_splash = open(syslinux_target + 'boot.msg', 'w')
878     isolinux_splash.write(generate_isolinux_splash(grml_flavour))
879     isolinux_splash.close( )
880
881
882 def handle_iso(iso, device):
883     """Main logic for mounting ISOs and copying files.
884
885     @iso: full path to the ISO that should be installed to the specified device
886     @device: partition where the specified ISO should be installed to"""
887
888     logging.info("Using ISO %s" % iso)
889
890     if os.path.isdir(iso):
891         logging.critical("TODO: /live/image handling not yet implemented - sorry") # TODO
892         sys.exit(1)
893
894     iso_mountpoint = tempfile.mkdtemp()
895     register_tmpfile(iso_mountpoint)
896     remove_iso_mountpoint = True
897
898     if not os.path.isfile(iso):
899         logging.critical("Fatal: specified ISO %s could not be read" % iso)
900         cleanup()
901         sys.exit(1)
902
903     try:
904         mount(iso, iso_mountpoint, ["-o", "loop", "-t", "iso9660"])
905     except CriticalException, error:
906         logging.critical("Fatal: %s" % error)
907         sys.exit(1)
908
909     if os.path.isdir(device):
910         logging.info("Specified target is a directory, not mounting therefor.")
911         device_mountpoint = device
912         remove_device_mountpoint = False
913         # skip_mbr = True
914     else:
915         device_mountpoint = tempfile.mkdtemp()
916         register_tmpfile(device_mountpoint)
917         remove_device_mountpoint = True
918         try:
919             mount(device, device_mountpoint, "")
920         except CriticalException, error:
921             logging.critical("Fatal: %s" % error)
922             cleanup()
923
924     try:
925         grml_flavour = identify_grml_flavour(iso_mountpoint)
926         logging.info("Identified grml flavour \"%s\"." % grml_flavour)
927         install_iso_files(grml_flavour, iso_mountpoint, device_mountpoint)
928     except TypeError:
929         logging.critical("Fatal: a critical error happend during execution (not a grml ISO?), giving up")
930         sys.exit(1)
931     finally:
932         if os.path.isdir(iso_mountpoint) and remove_iso_mountpoint:
933             unmount(iso_mountpoint, "")
934             os.rmdir(iso_mountpoint)
935             unregister_tmpfile(iso_mountpoint)
936         if remove_device_mountpoint:
937             unmount(device_mountpoint, "")
938             if os.path.isdir(device_mountpoint):
939                 os.rmdir(device_mountpoint)
940                 unregister_tmpfile(device_mountpoint)
941
942
943 def handle_mbr(device):
944     """TODO"""
945
946     # install MBR
947     # if not options.mbr:
948     #     logging.info("You are NOT using the --mbr option. Consider using it if your device does not boot.")
949     # else:
950     # make sure we install MBR on /dev/sdX and not /dev/sdX#
951
952     # make sure we have syslinux available
953     # if options.mbr:
954     if not options.skipmbr:
955         if not which("syslinux") and not options.copyonly and not options.dryrun:
956             logging.critical('Sorry, syslinux not available. Exiting.')
957             logging.critical('Please install syslinux or consider using the --grub option.')
958             sys.exit(1)
959
960     if not options.skipmbr:
961         if device[-1:].isdigit():
962             mbr_device = re.match(r'(.*?)\d*$', device).group(1)
963
964         try:
965             install_mbr(mbr_device)
966         except IOError, error:
967             logging.critical("Execution failed: %s", error)
968             sys.exit(1)
969         except Exception, error:
970             logging.critical("Execution failed: %s", error)
971             sys.exit(1)
972
973
974 def handle_vfat(device):
975     """TODO"""
976
977     # make sure we have mkfs.vfat available
978     if options.fat16 and not options.force:
979         if not which("mkfs.vfat") and not options.copyonly and not options.dryrun:
980             logging.critical('Sorry, mkfs.vfat not available. Exiting.')
981             logging.critical('Please make sure to install dosfstools.')
982             sys.exit(1)
983
984         # make sure the user is aware of what he is doing
985         f = raw_input("Are you sure you want to format the device with a fat16 filesystem? y/N ")
986         if f == "y" or f == "Y":
987             logging.info("Note: you can skip this question using the option --force")
988             mkfs_fat16(device)
989         else:
990             sys.exit(1)
991
992     # check for vfat filesystem
993     if device is not None and not os.path.isdir(device):
994         try:
995             check_for_fat(device)
996         except CriticalException, error:
997             logging.critical("Execution failed: %s", error)
998             sys.exit(1)
999
1000     if not check_for_usbdevice(device):
1001         print "Warning: the specified device %s does not look like a removable usb device." % device
1002         f = raw_input("Do you really want to continue? y/N ")
1003         if f == "y" or f == "Y":
1004             pass
1005         else:
1006             sys.exit(1)
1007
1008
1009 def handle_compat_warning(device):
1010     """TODO"""
1011
1012     # make sure we can replace old grml2usb script and warn user when using old way of life:
1013     if device.startswith("/mnt/external") or device.startswith("/mnt/usb") and not options.force:
1014         print "Warning: the semantics of grml2usb has changed."
1015         print "Instead of using grml2usb /path/to/iso %s you might" % device
1016         print "want to use grml2usb /path/to/iso /dev/... instead."
1017         print "Please check out the grml2usb manpage for details."
1018         f = raw_input("Do you really want to continue? y/N ")
1019         if f == "y" or f == "Y":
1020             pass
1021         else:
1022             sys.exit(1)
1023
1024
1025 def handle_logging():
1026     """TODO"""
1027
1028     if options.verbose:
1029         FORMAT = "%(asctime)-15s %(message)s"
1030         logging.basicConfig(level=logging.DEBUG, format=FORMAT)
1031     elif options.quiet:
1032         FORMAT = "Critial: %(message)s"
1033         logging.basicConfig(level=logging.CRITICAL, format=FORMAT)
1034     else:
1035         FORMAT = "Info: %(message)s"
1036         logging.basicConfig(level=logging.INFO, format=FORMAT)
1037
1038
1039 def handle_bootloader(device):
1040     """TODO"""
1041     # Install bootloader only if not using the --copy-only option
1042     if options.copyonly:
1043         logging.info("Not installing bootloader and its files as requested via option copyonly.")
1044     else:
1045         install_bootloader(device)
1046
1047
1048 def main():
1049     """Main function [make pylint happy :)]"""
1050
1051     if options.version:
1052         print os.path.basename(sys.argv[0]) + " " + PROG_VERSION
1053         sys.exit(0)
1054
1055     if len(args) < 2:
1056         parser.error("invalid usage")
1057
1058     # log handling
1059     handle_logging()
1060
1061     # make sure we have the appropriate permissions
1062     check_uid_root()
1063
1064     if options.dryrun:
1065         logging.info("Running in simulate mode as requested via option dry-run.")
1066
1067     # specified arguments
1068     device = args[len(args) - 1]
1069     isos = args[0:len(args) - 1]
1070
1071     # provide upgrade path
1072     handle_compat_warning(device)
1073
1074     # check for vfat partition
1075     handle_vfat(device)
1076
1077     # main operation (like installing files)
1078     for iso in isos:
1079         handle_iso(iso, device)
1080
1081     # install mbr
1082     handle_mbr(device)
1083
1084     handle_bootloader(device)
1085
1086     # finally be politely :)
1087     logging.info("Finished execution of grml2usb (%s). Have fun with your grml system." % PROG_VERSION)
1088
1089
1090 if __name__ == "__main__":
1091     try:
1092         main()
1093     except KeyboardInterrupt:
1094         logging.info("Received KeyboardInterrupt")
1095         cleanup()
1096
1097 ## END OF FILE #################################################################
1098 # vim:foldmethod=indent expandtab ai ft=python tw=120 fileencoding=utf-8