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