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