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