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 ################################################################################
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
21 prog_version = "0.0.1"
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
30 usage = "Usage: %prog [options] <ISO[s]> <partition>\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\
36 parser = OptionParser(usage=usage)
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")
66 (options, args) = parser.parse_args()
69 # wrapper functions {{{
71 # * implement argument handling
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."""
77 print "would execute %s now" % command
80 # * actual execution ;)
81 # * wrap subprocess.Popen()?
82 print "executing %s" % command
85 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
89 fpath, fname = os.path.split(program)
94 for path in os.environ["PATH"].split(os.pathsep):
95 exe_file = os.path.join(path, program)
102 def search_file(filename, search_path='/bin' + pathsep + '/usr/bin'):
103 """Given a search path, find file"""
105 paths = split(search_path, pathsep)
107 for current_dir, directories, files in os.walk(path):
108 if exists(join(current_dir, filename)):
112 return abspath(join(current_dir, filename))
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).")
124 def install_syslinux(device):
126 """Install syslinux on specified device."""
127 print("debug: syslinux %s [TODO]") % device
129 # syslinux -d boot/isolinux /dev/usb-sdb1
132 def generate_grub_config(grml_flavour):
133 """Generate grub configuration for use via menu,lst"""
136 # * what about system using grub2 without having grub available?
139 grml_name = grml_flavour
144 # color red/blue green/black
145 splashimage=/boot/grub/splash.xpm.gz
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
154 # TODO: extend configuration :)
158 def generate_isolinux_splash(grml_flavour):
159 """Generate bootsplash for isolinux/syslinux"""
162 # * adjust last bootsplash line
164 grml_name = grml_flavour
167 \ f17
\f\18/boot/isolinux/logo.16
169 Some information and boot options available via keys F2 - F10. http://grml.org/
173 def generate_syslinux_config(grml_flavour):
174 """Generate configuration for use in syslinux.cfg"""
177 # * unify isolinux and syslinux setup ("INCLUDE /boot/...")
179 grml_name = grml_flavour
182 # use this to control the bootup via a serial port
187 DISPLAY /boot/isolinux/boot.msg
188 F1 /boot/isolinux/boot.msg
197 F10 /boot/isolinux/f10
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
203 # TODO: extend configuration :)
207 def install_grub(device):
208 """Install grub on specified device."""
209 print("grub-install %s") % device
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)
223 install_syslinux(device)
226 def isWriteable(device):
227 """Check if the device is writeable for the current user"""
230 raise "WrongArguments", "no device for checking write permissions"
232 if not os.path.exists(device):
235 return os.access(device, os.W_OK) and os.access(device, os.R_OK)
237 def install_mbr(device):
238 """Install a default master boot record on given device
240 @device: device where MBR should be installed to"""
242 if not isWriteable(device):
243 raise IOError, "device not writeable for user"
245 lilo = './lilo/lilo.static' # FIXME
248 raise Exception, "lilo executable not available."
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"])
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"])
258 # lilo's mbr is broken, use the one from syslinux instead:
259 print("debug: cat /usr/lib/syslinux/mbr.bin > %s") % device
261 # FIXME: use Popen instead?
262 retcode = subprocess.call("cat /usr/lib/syslinux/mbr.bin > "+ device, shell=True)
264 print >>sys.stderr, "Error copying MBR to device", -retcode
266 print >>sys.stderr, "Execution failed:", e
269 def loopback_mount(iso, target):
270 """Loopback mount specified ISO on given target"""
272 print("mount -o loop %s %s") % (iso, target)
275 def check_for_vat(partition):
276 """Check whether specified partition is VFAT/FAT16 filesystem"""
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()
283 if udev_info.returncode == 2:
284 print("failed to read device %s - wrong UID / permissions?") % partition
287 if filesystem != "vfat":
291 # * check for ID_FS_VERSION=FAT16 as well?
294 print("Sorry, /lib/udev/vol_id not available.")
297 def mkdir(directory):
298 """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
299 if not os.path.isdir(directory):
301 os.makedirs(directory)
306 def copy_grml_files(grml_flavour, iso_mount, target):
307 """Copy files from ISO on given target"""
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?
314 squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
315 squashfs_target = target + '/live/'
316 mkdir(squashfs_target)
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"])
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'])
326 release_target = target + '/boot/release/' + grml_flavour
327 mkdir(release_target)
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'])
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'])
337 isolinux_target = target + '/boot/isolinux/'
338 mkdir(isolinux_target)
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'])
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])
349 grub_target = target + '/boot/grub/'
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'])
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'])
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( )
363 syslinux_target = target + '/boot/isolinux/'
364 mkdir(syslinux_target)
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( )
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( )
377 def uninstall_files(device):
378 """Get rid of all grml files on specified device"""
384 def identify_grml_flavour(mountpath):
385 """Get name of grml flavour"""
387 version_file = search_file('grml-version', mountpath)
388 file = open(version_file, 'r')
389 grml_info = file.readline()
391 grml_flavour = re.match(r'[\w-]*', grml_info).group()
398 print("%s %s")% (os.path.basename(sys.argv[0]), prog_version)
402 parser.error("invalid usage")
406 device = args[len(args) - 1]
407 isos = args[0:len(args) - 1]
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.'
415 # * check for valid blockdevice, vfat and mount functions
416 # if device is not None:
417 # check_for_vat(device)
418 # mount_target(partition)
421 target = '/mnt/usb-sdb1'
424 # * it doesn't need to be a ISO, could be /live/image as well
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
432 grml_flavour = identify_grml_flavour(iso_mount)
433 print("debug: grml_flavour = %s") % grml_flavour
435 grml_flavour_short = grml_flavour.replace('-','')
436 print("debug: grml_flavour_short = %s") % grml_flavour_short
438 # copy_grml_files(grml_flavour, iso_mount, target)
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)
448 print >>sys.stderr, "Execution failed:", e
451 print >>sys.stderr, "Execution failed:", e
454 install_bootloader(device)
456 if __name__ == "__main__":
459 ## END OF FILE #################################################################
460 # vim:foldmethod=marker expandtab ai ft=python tw=120