Some code cleanups to make pylint happier ;)
[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 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 * improve error handling :)
17 * implement mount handling
18 * log wrapper (-> logging module)
19 * implement logic for storing information about copied files
20   -> register every single file?
21 * trap handling (like unmount devices when interrupting?)
22 * get rid of all TODOs in code :)
23 * graphical version
24 """
25
26 import os, re, subprocess, sys, tempfile
27 from optparse import OptionParser
28 from os.path import exists, join, abspath
29 from os import pathsep
30 # TODO string.split() is deprecated - replace?
31 #      -> http://docs.python.org/library/string.html#deprecated-string-functions
32 from string import split
33
34 PROG_VERSION = "0.0.1"
35
36 # cmdline parsing
37 # TODO
38 # * --copy-only?
39 # * --bootloader-only?
40 usage = "Usage: %prog [options] <ISO[s]> <partition>\n\
41 \n\
42 %prog installs a grml ISO to an USB device to be able to boot from it.\n\
43 Make sure you have at least a grml ISO or a running grml system,\n\
44 syslinux (just run 'aptitude install syslinux' on Debian-based systems)\n\
45 and root access."
46
47 parser = OptionParser(usage=usage)
48 parser.add_option("--bootoptions", dest="bootoptions",
49                   action="store", type="string",
50                   help="use specified bootoptions as defaut")
51 parser.add_option("--dry-run", dest="dryrun", action="store_true",
52                   help="do not actually execute any commands")
53 parser.add_option("--fat16", dest="fat16", action="store_true",
54                   help="format specified partition with FAT16")
55 parser.add_option("--force", dest="force", action="store_true",
56                   help="force any actions requiring manual interaction")
57 parser.add_option("--grub", dest="grub", action="store_true",
58                   help="install grub bootloader instead of syslinux")
59 parser.add_option("--initrd", dest="initrd", action="store", type="string",
60                   help="install specified initrd instead of the default")
61 parser.add_option("--kernel", dest="kernel", action="store", type="string",
62                   help="install specified kernel instead of the default")
63 parser.add_option("--mbr", dest="mbr", action="store_true",
64                   help="install master boot record (MBR) on the device")
65 parser.add_option("--squashfs", dest="squashfs", action="store", type="string",
66                   help="install specified squashfs file instead of the default")
67 parser.add_option("--uninstall", dest="uninstall", action="store_true",
68                   help="remove grml ISO files")
69 parser.add_option("--verbose", dest="verbose", action="store_true",
70                   help="enable verbose mode")
71 parser.add_option("-v", "--version", dest="version", action="store_true",
72                   help="display version and exit")
73 (options, args) = parser.parse_args()
74
75
76 def execute(f, *args):
77     """Wrapper for executing a command. Either really executes
78     the command (default) or when using --dry-run commandline option
79     just displays what would be executed."""
80     # demo: execute(subprocess.Popen, (["ls", "-la"]))
81     if options.dryrun:
82         print "would execute %s(%s) now" % (f, args)
83     else:
84         return f(*args)
85
86
87 def is_exe(fpath):
88     """Check whether a given file can be executed
89
90     @fpath: full path to file
91     @return:"""
92     return os.path.exists(fpath) and os.access(fpath, os.X_OK)
93
94
95 def which(program):
96     """Check whether a given program is available in PATH
97
98     @program: name of executable"""
99     fpath, fname = os.path.split(program)
100     if fpath:
101         if is_exe(program):
102             return program
103     else:
104         for path in os.environ["PATH"].split(os.pathsep):
105             exe_file = os.path.join(path, program)
106             if is_exe(exe_file):
107                 return exe_file
108
109     return None
110
111
112 def search_file(filename, search_path='/bin' + pathsep + '/usr/bin'):
113     """Given a search path, find file"""
114     file_found = 0
115     paths = split(search_path, pathsep)
116     for path in paths:
117         for current_dir, directories, files in os.walk(path):
118             if exists(join(current_dir, filename)):
119                 file_found = 1
120                 break
121     if file_found:
122         return abspath(join(current_dir, filename))
123     else:
124         return None
125
126
127 def check_uid_root():
128     """Check for root permissions"""
129     if not os.geteuid()==0:
130         sys.exit("Error: please run this script with uid 0 (root).")
131
132
133 def install_syslinux(device):
134     # TODO
135     """Install syslinux on specified device."""
136     print("debug: syslinux %s [TODO]") % device
137
138     # syslinux -d boot/isolinux /dev/usb-sdb1
139
140
141 def generate_grub_config(grml_flavour):
142     """Generate grub configuration for use via menu,lst"""
143
144     # TODO
145     # * what about system using grub2 without having grub available?
146     # * support grub2
147
148     grml_name = grml_flavour
149
150     return("""\
151 # misc options:
152 timeout 30
153 # color red/blue green/black
154 splashimage=/boot/grub/splash.xpm.gz
155 foreground  = 000000
156 background  = FFCC33
157
158 # define entries:
159 title %(grml_name)s  - Default boot (using 1024x768 framebuffer)
160 kernel /boot/release/%(grml_name)s/linux26 apm=power-off lang=us vga=791 quiet boot=live nomce module=%(grml_name)s
161 initrd /boot/release/%(grml_name)s/initrd.gz
162
163 # TODO: extend configuration :)
164 """ % locals())
165
166
167 def generate_isolinux_splash(grml_flavour):
168     """Generate bootsplash for isolinux/syslinux"""
169
170     # TODO
171     # * adjust last bootsplash line
172
173     grml_name = grml_flavour
174
175     return("""\
176 \ f17\f\18/boot/isolinux/logo.16
177
178 Some information and boot options available via keys F2 - F10. http://grml.org/
179 %(grml_name)s
180 """ % locals())
181
182 def generate_syslinux_config(grml_flavour):
183     """Generate configuration for use in syslinux.cfg"""
184
185     # TODO
186     # * unify isolinux and syslinux setup ("INCLUDE /boot/...")
187
188     grml_name = grml_flavour
189
190     return("""\
191 # use this to control the bootup via a serial port
192 # SERIAL 0 9600
193 DEFAULT grml
194 TIMEOUT 300
195 PROMPT 1
196 DISPLAY /boot/isolinux/boot.msg
197 F1 /boot/isolinux/boot.msg
198 F2 /boot/isolinux/f2
199 F3 /boot/isolinux/f3
200 F4 /boot/isolinux/f4
201 F5 /boot/isolinux/f5
202 F6 /boot/isolinux/f6
203 F7 /boot/isolinux/f7
204 F8 /boot/isolinux/f8
205 F9 /boot/isolinux/f9
206 F10 /boot/isolinux/f10
207
208 LABEL grml
209 KERNEL /boot/release/%(grml_name)s/linux26
210 APPEND initrd=/boot/release/%(grml_name)s/initrd.gz apm=power-off lang=us boot=live nomce module=%(grml_name)s
211
212 # TODO: extend configuration :)
213 """ % locals())
214
215
216 def install_grub(device):
217     """Install grub on specified device."""
218     print("grub-install %s") % device
219
220
221 def install_bootloader(partition):
222     """Install bootloader on device."""
223     # Install bootloader on the device (/dev/sda),
224     # not on the partition itself (/dev/sda1)
225     if partition[-1:].isdigit():
226         device = re.match(r'(.*?)\d*$', partition).group(1)
227     else:
228         device = partition
229
230     if options.grub:
231         install_grub(device)
232     else:
233         install_syslinux(device)
234
235
236 def is_writeable(device):
237     """Check if the device is writeable for the current user"""
238
239     if not device:
240         return False
241         #raise Exception, "no device for checking write permissions"
242
243     if not os.path.exists(device):
244         return False
245
246     return os.access(device, os.W_OK) and os.access(device, os.R_OK)
247
248 def install_mbr(device):
249     """Install a default master boot record on given device
250
251     @device: device where MBR should be installed to"""
252
253     if not is_writeable(device):
254         raise IOError, "device not writeable for user"
255
256     lilo = './lilo/lilo.static' # FIXME
257
258     if not is_exe(lilo):
259         raise Exception, "lilo executable not available."
260
261     # to support -A for extended partitions:
262     print("debug: ./lilo/lilo.static -S /dev/null -M %s ext") % device
263     proc = subprocess.Popen(["./lilo/lilo.static", "-S", "/dev/null", "-M", device, "ext"])
264     proc.wait()
265     if proc.returncode != 0:
266         raise Exception, "error executing lilo"
267
268     # activate partition:
269     print("debug: ./lilo/lilo.static -S /dev/null -A %s 1") % device
270     proc = subprocess.Popen(["./lilo/lilo.static", "-S", "/dev/null", "-A", device, "1"])
271     proc.wait()
272     if proc.returncode != 0:
273         raise Exception, "error executing lilo"
274
275     # lilo's mbr is broken, use the one from syslinux instead:
276     print("debug: cat /usr/lib/syslinux/mbr.bin > %s") % device
277     try:
278         # TODO use Popen instead?
279         retcode = subprocess.call("cat /usr/lib/syslinux/mbr.bin > "+ device, shell=True)
280         if retcode < 0:
281             print >> sys.stderr, "Error copying MBR to device", -retcode
282     except OSError, error:
283         print >> sys.stderr, "Execution failed:", error
284
285
286 def loopback_mount(iso, target):
287     """Loopback mount specified ISO on given target
288
289     @iso: name of ISO that should be mounted
290     @target: directory where the ISO should be mounted to"""
291
292     print("mount -o loop %s %s") % (iso, target)
293
294
295 def check_for_vat(partition):
296     """Check whether specified partition is a valid VFAT/FAT16 filesystem
297
298     @partition: device name of partition"""
299
300     try:
301         udev_info = subprocess.Popen(["/lib/udev/vol_id", "-t",
302             partition],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
303         filesystem = udev_info.communicate()[0].rstrip()
304
305         if udev_info.returncode == 2:
306             print("failed to read device %s - wrong UID / permissions?") % partition
307             return 1
308
309         if filesystem != "vfat":
310             return(1)
311
312         # TODO
313         # * check for ID_FS_VERSION=FAT16 as well?
314
315     except OSError:
316         print("Sorry, /lib/udev/vol_id not available.")
317         return 1
318
319 def mkdir(directory):
320     """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
321
322     if not os.path.isdir(directory):
323         try:
324             os.makedirs(directory)
325         except OSError:
326             # just silently pass as it's just fine it the directory exists
327             pass
328
329
330 def copy_grml_files(grml_flavour, iso_mount, target):
331     """Copy files from ISO on given target"""
332
333     # TODO
334     # * provide alternative search_file() if file information is stored in a config.ini file?
335     # * catch "install: .. No space left on device" & CO
336     # * abstract copy logic to make the code shorter?
337
338     squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
339     squashfs_target = target + '/live/'
340     mkdir(squashfs_target)
341
342     # use install(1) for now to make sure we can write the files afterwards as normal user as well
343     print("debug: copy squashfs to %s") % target + '/live/' + grml_flavour + '.squashfs'
344     subprocess.Popen(["install", "--mode=664", squashfs, squashfs_target + grml_flavour + ".squashfs"])
345
346     filesystem_module = search_file('filesystem.module', iso_mount)
347     print("debug: copy filesystem.module to %s") % squashfs_target + grml_flavour + '.module'
348     subprocess.Popen(["install", "--mode=664", filesystem_module, squashfs_target + grml_flavour + '.module'])
349
350     release_target = target + '/boot/release/' + grml_flavour
351     mkdir(release_target)
352
353     kernel = search_file('linux26', iso_mount)
354     print("debug: copy kernel to %s") % release_target + '/linux26'
355     subprocess.Popen(["install", "--mode=664", kernel, release_target + '/linux26'])
356
357     initrd = search_file('initrd.gz', iso_mount)
358     print("debug: copy initrd to %s") % release_target + '/initrd.gz'
359     subprocess.Popen(["install", "--mode=664", initrd, release_target + '/initrd.gz'])
360
361     isolinux_target = target + '/boot/isolinux/'
362     mkdir(isolinux_target)
363
364     logo = search_file('logo.16', iso_mount)
365     print("debug: copy logo.16 to %s") % isolinux_target + 'logo.16'
366     subprocess.Popen(["install", "--mode=664", logo, isolinux_target + 'logo.16'])
367
368     for ffile in 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10':
369         bootsplash = search_file(ffile, iso_mount)
370         print("debug: copy %s to %s") % (bootsplash, isolinux_target + ffile)
371         subprocess.Popen(["install", "--mode=664", bootsplash, isolinux_target + ffile])
372
373     grub_target = target + '/boot/grub/'
374     mkdir(grub_target)
375
376     print("debug: copy grub/splash.xpm.gz to %s") % grub_target + 'splash.xpm.gz'
377     subprocess.Popen(["install", "--mode=664", 'grub/splash.xpm.gz', grub_target + 'splash.xpm.gz'])
378
379     print("debug: copy grub/stage2_eltorito to %s") % grub_target + 'stage2_eltorito'
380     subprocess.Popen(["install", "--mode=664", 'grub/stage2_eltorito', grub_target + 'stage2_eltorito'])
381
382     print("debug: generating grub configuration %s") % grub_target + 'menu.lst'
383     grub_config_file = open(grub_target + 'menu.lst', 'w')
384     grub_config_file.write(generate_grub_config(grml_flavour))
385     grub_config_file.close( )
386
387     syslinux_target = target + '/boot/isolinux/'
388     mkdir(syslinux_target)
389
390     print("debug: generating syslinux configuration %s") % syslinux_target + 'syslinux.cfg'
391     syslinux_config_file = open(syslinux_target + 'syslinux.cfg', 'w')
392     syslinux_config_file.write(generate_syslinux_config(grml_flavour))
393     syslinux_config_file.close( )
394
395     print("debug: generating isolinux/syslinux splash %s") % syslinux_target + 'boot.msg'
396     isolinux_splash = open(syslinux_target + 'boot.msg', 'w')
397     isolinux_splash.write(generate_isolinux_splash(grml_flavour))
398     isolinux_splash.close( )
399
400
401 def uninstall_files(device):
402     """Get rid of all grml files on specified device"""
403
404     # TODO
405     print("TODO: %s") % device
406
407
408 def identify_grml_flavour(mountpath):
409     """Get name of grml flavour
410
411     @mountpath: path where the grml ISO is mounted to
412     @return: name of grml-flavour"""
413
414     version_file = search_file('grml-version', mountpath)
415
416     tmpfile = open(version_file, 'r')
417     grml_info = tmpfile.readline()
418     #tmpfile.close # pylint: Statement seems to have no effect
419
420     grml_flavour = re.match(r'[\w-]*', grml_info).group()
421     return grml_flavour
422
423
424 def main():
425     """Main function [make pylint happy :)]"""
426
427     if options.version:
428         print("%s %s")% (os.path.basename(sys.argv[0]), PROG_VERSION)
429         sys.exit(0)
430
431     if len(args) < 2:
432         parser.error("invalid usage")
433
434     # check_uid_root()
435
436     device = args[len(args) - 1]
437     isos = args[0:len(args) - 1]
438
439     if not which("syslinux"):
440         print >> sys.stderr, 'Sorry, syslinux not available. Exiting.'
441         print >> sys.stderr, 'Please install syslinux or consider using the --grub option.'
442         sys.exit(1)
443
444     # TODO
445     # * check for valid blockdevice, vfat and mount functions
446     # if device is not None:
447         # check_for_vat(device)
448         # mount_target(partition)
449
450     # TODO
451     # target = '/mnt/usb-sdb1'
452     target = tempfile.mkdtemp()
453     print("debug: target = %s") % target
454
455     # TODO
456     # * it doesn't need to be a ISO, could be /live/image as well
457     for iso in isos:
458         print("debug: iso = %s") % iso
459         # loopback_mount(iso)
460         iso_mount = '/mnt/test' # FIXME
461         loopback_mount(iso, target) # FIXME s/target/iso_mount/
462         # copy_grml_files(iso, target)
463         # loopback_unmount(iso)
464
465         grml_flavour = identify_grml_flavour(iso_mount)
466         print("debug: grml_flavour = %s") % grml_flavour
467
468         grml_flavour_short = grml_flavour.replace('-','')
469         print("debug: grml_flavour_short = %s") % grml_flavour_short
470
471         # TODO - re-enable :)
472         # copy_grml_files(grml_flavour, iso_mount, target)
473
474     if options.mbr:
475         # make sure we install MBR on /dev/sdX and not /dev/sdX#
476         if device[-1:].isdigit():
477             device = re.match(r'(.*?)\d*$', device).group(1)
478
479         try:
480             install_mbr(device)
481         except IOError, error:
482             print >> sys.stderr, "Execution failed:", error
483             sys.exit(1)
484         except Exception, error:
485             print >> sys.stderr, "Execution failed:", error
486             sys.exit(1)
487
488     install_bootloader(device)
489
490     if os.path.isdir(target):
491         os.rmdir(target)
492
493 if __name__ == "__main__":
494     main()
495
496 ## END OF FILE #################################################################
497 # vim:foldmethod=marker expandtab ai ft=python tw=120 fileencoding=utf-8