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