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