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)
38 parser.add_option("--bootoptions", dest="bootoptions", action="store", type="string",
39 help="use specified bootoptions as defaut")
40 parser.add_option("--dry-run", dest="dryrun", action="store_true",
41 help="do not actually execute any commands")
42 parser.add_option("--fat16", dest="fat16", action="store_true",
43 help="format specified partition with FAT16")
44 parser.add_option("--force", dest="force", action="store_true",
45 help="force any actions requiring manual interaction")
46 parser.add_option("--grub", dest="grub", action="store_true",
47 help="install grub bootloader instead of syslinux")
48 parser.add_option("--initrd", dest="initrd", action="store", type="string",
49 help="install specified initrd instead of the default")
50 parser.add_option("--kernel", dest="kernel", action="store", type="string",
51 help="install specified kernel instead of the default")
52 parser.add_option("--mbr", dest="mbr", action="store_true",
53 help="install master boot record (MBR) on the device")
54 parser.add_option("--squashfs", dest="squashfs", action="store", type="string",
55 help="install specified squashfs file instead of the default")
56 parser.add_option("--uninstall", dest="uninstall", action="store_true",
57 help="remove grml ISO files")
58 parser.add_option("--verbose", dest="verbose", action="store_true",
59 help="enable verbose mode")
60 parser.add_option("-v", "--version", dest="version", action="store_true",
61 help="display version and exit")
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 # TODO: actual execution ;)
74 print "executing %s" % command
78 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
80 fpath, fname = os.path.split(program)
85 for path in os.environ["PATH"].split(os.pathsep):
86 exe_file = os.path.join(path, program)
92 def search_file(filename, search_path='/bin' + pathsep + '/usr/bin'):
93 """Given a search path, find file"""
95 paths = split(search_path, pathsep)
97 for current_dir, directories, files in os.walk(path):
98 if exists(join(current_dir, filename)):
102 return abspath(join(current_dir, filename))
108 def check_uid_root():
109 """Check for root permissions"""
110 if not os.geteuid()==0:
111 sys.exit("Error: please run this script with uid 0 (root).")
114 def install_syslinux(device):
115 """Install syslinux on specified device."""
116 print("debug: syslinux %s [TODO]") % device
119 def generate_grub_config(grml_flavour):
120 """Generate grub configuration for use via menu,lst"""
123 # * what about system using grub2 without having grub available?
126 grml_name = grml_flavour
131 # color red/blue green/black
132 splashimage=/boot/grub/splash.xpm.gz
137 title %(grml_name)s - Default boot (using 1024x768 framebuffer)
138 kernel /boot/release/%(grml_name)s/linux26 apm=power-off lang=us vga=791 quiet boot=live nomce module=%(grml_name)s
139 initrd /boot/release/%(grml_name)s/initrd.gz
141 # TODO: extend configuration :)
145 def generate_isolinux_splash(grml_flavour):
146 """Generate bootsplash for isolinux/syslinux"""
149 # * adjust last bootsplash line
151 grml_name = grml_flavour
154 \ f17
\f\18/boot/isolinux/logo.16
156 Some information and boot options available via keys F2 - F10. http://grml.org/
160 def generate_syslinux_config(grml_flavour):
161 """Generate configuration for use in syslinux.cfg"""
164 # * unify isolinux and syslinux setup ("INCLUDE /boot/...")
166 grml_name = grml_flavour
169 # use this to control the bootup via a serial port
174 DISPLAY /boot/isolinux/boot.msg
175 F1 /boot/isolinux/boot.msg
184 F10 /boot/isolinux/f10
187 KERNEL /boot/release/%(grml_name)s/linux26
188 APPEND initrd=/boot/release/%(grml_name)s/initrd.gz apm=power-off lang=us boot=live nomce module=%(grml_name)s
190 # TODO: extend configuration :)
194 def install_grub(device):
195 """Install grub on specified device."""
196 print("grub-install %s") % device
199 def install_bootloader(partition):
200 """Install bootloader on device."""
201 # Install bootloader on the device (/dev/sda), not on the partition itself (/dev/sda1)
202 if partition[-1:].isdigit():
203 device = re.match(r'(.*?)\d*$', partition).group(1)
210 install_syslinux(device)
213 def install_mbr(target):
214 """Install a default master boot record on given target"""
217 # Command logic (all executed *without* mounted device):
218 # lilo -S /dev/null -M /dev/usb-sdb ext
219 # lilo -S /dev/null -A /dev/usb-sdb 1
220 # cat /usr/lib/syslinux/mbr.bin > /dev/usb-sdb
221 # syslinux -d boot/isolinux /dev/usb-sdb1
223 def loopback_mount(iso, target):
224 """Loopback mount specified ISO on given target"""
226 print("mount -o loop %s %s") % (iso, target)
229 def check_for_vat(partition):
230 """Check whether specified partition is VFAT/FAT16 filesystem"""
233 udev_info = subprocess.Popen(["/lib/udev/vol_id", "-t",
234 partition],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
235 filesystem = udev_info.communicate()[0].rstrip()
237 if udev_info.returncode == 2:
238 print("failed to read device %s - wrong UID / permissions?") % partition
241 if filesystem != "vfat":
244 # TODO: check for ID_FS_VERSION=FAT16 as well?
247 print("Sorry, /lib/udev/vol_id not available.")
250 def mkdir(directory):
251 """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
252 if not os.path.isdir(directory):
254 os.makedirs(directory)
259 def copy_grml_files(grml_flavour, iso_mount, target):
260 """Copy files from ISO on given target"""
263 # * provide alternative search_file() if file information is stored in a config.ini file?
264 # * catch "install: .. No space left on device" & CO
265 # * abstract copy logic to make the code shorter?
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()
348 (options, args) = parser.parse_args()
351 print("%s %s")% (os.path.basename(sys.argv[0]), prog_version)
355 parser.error("invalid usage")
359 device = args[len(args) - 1]
360 isos = args[0:len(args) - 1]
362 if not which("syslinux"):
363 print("Sorry, syslinux not available. Exiting.")
364 print("Please install syslinux or consider using the --grub option.")
367 # TODO check for valid blockdevice, vfat and mount functions
368 # if device is not None:
369 # check_for_vat(device)
370 # mount_target(partition)
373 target = '/mnt/usb-sdb1'
375 # TODO it doesn't need to be a ISO, could be /live/image as well
377 print("debug: iso = %s") % iso
378 # loopback_mount(iso)
379 # copy_grml_files(iso, target)
380 # loopback_unmount(iso)
381 iso_mount = '/mnt/test' # FIXME
383 grml_flavour = identify_grml_flavour(iso_mount)
384 print("debug: grml_flavour = %s") % grml_flavour
386 grml_flavour_short = grml_flavour.replace('-','')
387 print("debug: grml_flavour_short = %s") % grml_flavour_short
389 copy_grml_files(grml_flavour, iso_mount, target)
393 print("debug: would install MBR now")
395 install_bootloader(device)
397 if __name__ == "__main__":
400 ## END OF FILE #################################################################
401 # vim:foldmethod=marker expandtab ai ft=python tw=120