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)
14 # * trap handling (umount devices when interrupting?)
15 # * integrate https://www.mirbsd.org/cvs.cgi/src/sys/arch/i386/stand/mbr/mbr.S?rev=HEAD;content-type=text%2Fplain ?
16 # -> gcc -D_ASM_SOURCE -D__BOOT_VER=\"GRML\" -DBOOTMANAGER -c mbr.S; ld
17 # -nostdlib -Ttext 0 -N -Bstatic --oformat binary mbr.o -o mbrmgr
19 prog_version = "0.0.1"
21 import os, re, subprocess, sys
22 from optparse import OptionParser
23 from os.path import exists, join, abspath
24 from os import pathsep
25 from string import split
28 usage = "Usage: %prog [options] <ISO[s]> <partition>\n\
30 %prog installs a grml ISO to an USB device to be able to boot from it.\n\
31 Make sure you have at least a grml ISO or a running grml system,\n\
32 syslinux (just run 'aptitude install syslinux' on Debian-based systems)\n\
34 parser = OptionParser(usage=usage)
36 parser.add_option("--bootoptions", dest="bootoptions", action="store", type="string",
37 help="use specified bootoptions as defaut")
38 parser.add_option("--dry-run", dest="dryrun", action="store_true",
39 help="do not actually execute any commands")
40 parser.add_option("--fat16", dest="fat16", action="store_true",
41 help="format specified partition with FAT16")
42 parser.add_option("--force", dest="force", action="store_true",
43 help="force any actions requiring manual interaction")
44 parser.add_option("--grub", dest="grub", action="store_true",
45 help="install grub bootloader instead of syslinux")
46 parser.add_option("--initrd", dest="initrd", action="store", type="string",
47 help="install specified initrd instead of the default")
48 parser.add_option("--kernel", dest="kernel", action="store", type="string",
49 help="install specified kernel instead of the default")
50 parser.add_option("--mbr", dest="mbr", action="store_true",
51 help="install master boot record (MBR) on the device")
52 parser.add_option("--squashfs", dest="squashfs", action="store", type="string",
53 help="install specified squashfs file instead of the default")
54 parser.add_option("--uninstall", dest="uninstall", action="store_true",
55 help="remove grml ISO files")
56 parser.add_option("--verbose", dest="verbose", action="store_true",
57 help="enable verbose mode")
58 parser.add_option("-v", "--version", dest="version", action="store_true",
59 help="display version and exit")
61 (options, args) = parser.parse_args()
64 # wrapper functions {{{
65 # TODO: implement argument handling
67 """Wrapper for executing a command. Either really executes
68 the command (default) or when using --dry-run commandline option
69 just displays what would be executed."""
71 print "would execute %s now" % command
73 print "executing %s" % command
77 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
79 fpath, fname = os.path.split(program)
84 for path in os.environ["PATH"].split(os.pathsep):
85 exe_file = os.path.join(path, program)
91 def search_file(filename, search_path='/bin' + pathsep + '/usr/bin'):
92 """Given a search path, find file"""
94 paths = split(search_path, pathsep)
96 for current_dir, directories, files in os.walk(path):
97 if exists(join(current_dir, filename)):
101 return abspath(join(current_dir, filename))
107 def check_uid_root():
108 """Check for root permissions"""
109 if not os.geteuid()==0:
110 sys.exit("Error: please run this script with uid 0 (root).")
113 def install_syslinux(device):
114 """Install syslinux on specified device."""
115 print("debug: syslinux %s") % device
118 def generate_grub_config(grml_flavour):
119 """Generate grub configuration for use via menu,lst"""
122 # * what about system using grub2 without having grub available?
125 grml_name = grml_flavour
130 # color red/blue green/black
131 splashimage=/boot/grub/splash.xpm.gz
136 title %(grml_name)s - Default boot (using 1024x768 framebuffer)
137 kernel /boot/release/%(grml_name)s/linux26 apm=power-off lang=us vga=791 quiet boot=live nomce module=%(grml_name)s
138 initrd /boot/release/%(grml_name)s/initrd.gz
140 # TODO: extend configuration :)
144 def generate_isolinux_splash(grml_flavour):
145 """Generate bootsplash for isolinux/syslinux"""
148 # * adjust last bootsplash line
150 grml_name = grml_flavour
153 \ f17
\f\18/boot/isolinux/logo.16
155 Some information and boot options available via keys F2 - F10. http://grml.org/
159 def generate_syslinux_config(grml_flavour):
160 """Generate configuration for use in syslinux.cfg"""
163 # * unify isolinux and syslinux setup ("INCLUDE /boot/...")
165 grml_name = grml_flavour
168 # use this to control the bootup via a serial port
173 DISPLAY /boot/isolinux/boot.msg
174 F1 /boot/isolinux/boot.msg
183 F10 /boot/isolinux/f10
186 KERNEL /boot/release/%(grml_name)s/linux26
187 APPEND initrd=/boot/release/%(grml_name)s/initrd.gz apm=power-off lang=us boot=live nomce module=%(grml_name)s
189 # TODO: extend configuration :)
193 def install_grub(device):
194 """Install grub on specified device."""
195 print("grub-install %s") % device
198 def install_bootloader(partition):
199 """Install bootloader on device."""
200 # Install bootloader on the device (/dev/sda), not on the partition itself (/dev/sda1)
201 if partition[-1:].isdigit():
202 device = re.match(r'(.*?)\d*$', partition).group(1)
209 install_syslinux(device)
212 def install_mbr(target):
213 """Install a default master boot record on given target"""
216 # Command logic (all executed *without* mounted device):
217 # lilo -S /dev/null -M /dev/usb-sdb ext
218 # lilo -S /dev/null -A /dev/usb-sdb 1
219 # cat ./mbr.bin > /dev/usb-sdb
220 # syslinux -d boot/isolinux /dev/usb-sdb1
222 def loopback_mount(iso, target):
223 """Loopback mount specified ISO on given target"""
225 print("mount -o loop %s %s") % (iso, target)
228 def check_for_vat(partition):
229 """Check whether specified partition is VFAT/FAT16 filesystem"""
232 udev_info = subprocess.Popen(["/lib/udev/vol_id", "-t",
233 partition],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
234 filesystem = udev_info.communicate()[0].rstrip()
236 if udev_info.returncode == 2:
237 print("failed to read device %s - wrong UID / permissions?") % partition
240 if filesystem != "vfat":
243 # TODO: check for ID_FS_VERSION=FAT16 as well?
246 print("Sorry, /lib/udev/vol_id not available.")
249 def mkdir(directory):
250 """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
251 if not os.path.isdir(directory):
253 os.makedirs(directory)
258 def copy_grml_files(grml_flavour, iso_mount, target):
259 """Copy files from ISO on given target"""
262 # * provide alternative search_file() if file information is stored in a config.ini file?
263 # * catch "install: .. No space left on device" & CO
264 # * abstract copy logic to make the code shorter?
265 # * provide progress bar?
267 squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
268 squashfs_target = target + '/live/'
269 mkdir(squashfs_target)
271 # use install(1) for now to make sure we can write the files afterwards as normal user as well
272 print("debug: copy squashfs to %s") % target + '/live/' + grml_flavour + '.squashfs'
273 subprocess.Popen(["install", "--mode=664", squashfs, squashfs_target + grml_flavour + ".squashfs"])
275 filesystem_module = search_file('filesystem.module', iso_mount)
276 print("debug: copy filesystem.module to %s") % squashfs_target + grml_flavour + '.module'
277 subprocess.Popen(["install", "--mode=664", filesystem_module, squashfs_target + grml_flavour + '.module'])
279 release_target = target + '/boot/release/' + grml_flavour
280 mkdir(release_target)
282 kernel = search_file('linux26', iso_mount)
283 print("debug: copy kernel to %s") % release_target + '/linux26'
284 subprocess.Popen(["install", "--mode=664", kernel, release_target + '/linux26'])
286 initrd = search_file('initrd.gz', iso_mount)
287 print("debug: copy initrd to %s") % release_target + '/initrd.gz'
288 subprocess.Popen(["install", "--mode=664", initrd, release_target + '/initrd.gz'])
290 isolinux_target = target + '/boot/isolinux/'
291 mkdir(isolinux_target)
293 logo = search_file('logo.16', iso_mount)
294 print("debug: copy logo.16 to %s") % isolinux_target + 'logo.16'
295 subprocess.Popen(["install", "--mode=664", logo, isolinux_target + 'logo.16'])
297 for file in 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10':
298 bootsplash = search_file(file, iso_mount)
299 print("debug: copy %s to %s") % (bootsplash, isolinux_target + file)
300 subprocess.Popen(["install", "--mode=664", bootsplash, isolinux_target + file])
302 grub_target = target + '/boot/grub/'
305 print("debug: copy grub/splash.xpm.gz to %s") % grub_target + 'splash.xpm.gz'
306 subprocess.Popen(["install", "--mode=664", 'grub/splash.xpm.gz', grub_target + 'splash.xpm.gz'])
308 print("debug: copy grub/stage2_eltorito to %s") % grub_target + 'stage2_eltorito'
309 subprocess.Popen(["install", "--mode=664", 'grub/stage2_eltorito', grub_target + 'stage2_eltorito'])
311 print("debug: generating grub configuration %s") % grub_target + 'menu.lst'
312 grub_config_file = open(grub_target + 'menu.lst', 'w')
313 grub_config_file.write(generate_grub_config(grml_flavour))
314 grub_config_file.close( )
316 syslinux_target = target + '/boot/isolinux/'
317 mkdir(syslinux_target)
319 print("debug: generating syslinux configuration %s") % syslinux_target + 'syslinux.cfg'
320 syslinux_config_file = open(syslinux_target + 'syslinux.cfg', 'w')
321 syslinux_config_file.write(generate_syslinux_config(grml_flavour))
322 syslinux_config_file.close( )
324 print("debug: generating isolinux/syslinux splash %s") % syslinux_target + 'boot.msg'
325 isolinux_splash = open(syslinux_target + 'boot.msg', 'w')
326 isolinux_splash.write(generate_isolinux_splash(grml_flavour))
327 isolinux_splash.close( )
330 def uninstall_files(device):
331 """Get rid of all grml files on specified device"""
336 def identify_grml_flavour(mountpath):
337 """Get name of grml flavour"""
339 version_file = search_file('grml-version', mountpath)
340 file = open(version_file, 'r')
341 grml_info = file.readline()
343 grml_flavour = re.match(r'[\w-]*', grml_info).group()
349 print("%s %s")% (os.path.basename(sys.argv[0]), prog_version)
353 parser.error("invalid usage")
357 device = args[len(args) - 1]
358 isos = args[0:len(args) - 1]
360 if not which("syslinux"):
361 print("Sorry, syslinux not available. Exiting.")
362 print("Please install syslinux or consider using the --grub option.")
365 # TODO check for valid blockdevice, vfat and mount functions
366 # if device is not None:
367 # check_for_vat(device)
368 # mount_target(partition)
371 target = '/mnt/usb-sdb1'
373 # TODO it doesn't need to be a ISO, could be /live/image as well
375 print("debug: iso = %s") % iso
376 # loopback_mount(iso)
377 # copy_grml_files(iso, target)
378 # loopback_unmount(iso)
379 iso_mount = '/mnt/test' # FIXME
381 grml_flavour = identify_grml_flavour(iso_mount)
382 print("debug: grml_flavour = %s") % grml_flavour
384 grml_flavour_short = grml_flavour.replace('-','')
385 print("debug: grml_flavour_short = %s") % grml_flavour_short
387 copy_grml_files(grml_flavour, iso_mount, target)
391 print("debug: would install MBR now")
393 install_bootloader(device)
395 if __name__ == "__main__":
398 ## END OF FILE #################################################################
399 # vim:foldmethod=marker expandtab ai ft=python tw=120