6819481c91b091abd8e5fb0ad336371c7b22551e
[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)
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
18
19 prog_version = "0.0.1"
20
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
26
27 # cmdline parsing {{{
28 usage = "Usage: %prog [options] <ISO[s]> <partition>\n\
29 \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\
33 and root access."
34 parser = OptionParser(usage=usage)
35
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")
60
61 (options, args) = parser.parse_args()
62 # }}}
63
64 # wrapper functions {{{
65 # TODO: implement argument handling
66 def execute(command):
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."""
70     if options.dryrun:
71         print "would execute %s now" % command
72     else:
73         print "executing %s" % command
74
75 def which(program):
76     def is_exe(fpath):
77         return os.path.exists(fpath) and os.access(fpath, os.X_OK)
78
79     fpath, fname = os.path.split(program)
80     if fpath:
81         if is_exe(program):
82             return program
83     else:
84         for path in os.environ["PATH"].split(os.pathsep):
85             exe_file = os.path.join(path, program)
86             if is_exe(exe_file):
87                 return exe_file
88
89     return None
90
91 def search_file(filename, search_path='/bin' + pathsep + '/usr/bin'):
92    """Given a search path, find file"""
93    file_found = 0
94    paths = split(search_path, pathsep)
95    for path in paths:
96        for current_dir, directories, files in os.walk(path):
97            if exists(join(current_dir, filename)):
98               file_found = 1
99               break
100    if file_found:
101       return abspath(join(current_dir, filename))
102    else:
103       return None
104 # }}}
105
106
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).")
111
112
113 def install_syslinux(device):
114     """Install syslinux on specified device."""
115     print("debug: syslinux %s") % device
116
117
118 def generate_grub_config(grml_flavour):
119     """Generate grub configuration for use via menu,lst"""
120
121     # TODO:
122     # * what about system using grub2 without having grub available?
123     # * support grub2
124
125     grml_name = grml_flavour
126
127     return("""\
128 # misc options:
129 timeout 30
130 # color red/blue green/black
131 splashimage=/boot/grub/splash.xpm.gz
132 foreground  = 000000
133 background  = FFCC33
134
135 # define entries:
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
139
140 # TODO: extend configuration :)
141 """ % locals())
142
143
144 def generate_isolinux_splash(grml_flavour):
145     """Generate bootsplash for isolinux/syslinux"""
146
147     # TODO:
148     # * adjust last bootsplash line
149
150     grml_name = grml_flavour
151
152     return("""\
153 \ f17\f\18/boot/isolinux/logo.16
154
155 Some information and boot options available via keys F2 - F10. http://grml.org/
156 %(grml_name)s
157 """ % locals())
158
159 def generate_syslinux_config(grml_flavour):
160     """Generate configuration for use in syslinux.cfg"""
161
162     # TODO:
163     # * unify isolinux and syslinux setup ("INCLUDE /boot/...")
164
165     grml_name = grml_flavour
166
167     return("""\
168 # use this to control the bootup via a serial port
169 # SERIAL 0 9600
170 DEFAULT grml
171 TIMEOUT 300
172 PROMPT 1
173 DISPLAY /boot/isolinux/boot.msg
174 F1 /boot/isolinux/boot.msg
175 F2 /boot/isolinux/f2
176 F3 /boot/isolinux/f3
177 F4 /boot/isolinux/f4
178 F5 /boot/isolinux/f5
179 F6 /boot/isolinux/f6
180 F7 /boot/isolinux/f7
181 F8 /boot/isolinux/f8
182 F9 /boot/isolinux/f9
183 F10 /boot/isolinux/f10
184
185 LABEL grml
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
188
189 # TODO: extend configuration :)
190 """ % locals())
191
192
193 def install_grub(device):
194     """Install grub on specified device."""
195     print("grub-install %s") % device
196
197
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)
203     else:
204         device = partition
205
206     if options.grub:
207         install_grub(device)
208     else:
209         install_syslinux(device)
210
211
212 def install_mbr(target):
213     """Install a default master boot record on given target"""
214     print("TODO")
215
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
221
222 def loopback_mount(iso, target):
223     """Loopback mount specified ISO on given target"""
224
225     print("mount -o loop %s %s") % (iso, target)
226
227
228 def check_for_vat(partition):
229     """Check whether specified partition is VFAT/FAT16 filesystem"""
230
231     try:
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()
235
236         if udev_info.returncode == 2:
237             print("failed to read device %s - wrong UID / permissions?") % partition
238             return 1
239
240         if filesystem != "vfat":
241             return(1)
242
243         # TODO: check for ID_FS_VERSION=FAT16 as well?
244
245     except OSError:
246         print("Sorry, /lib/udev/vol_id not available.")
247         return 1
248
249 def mkdir(directory):
250     """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
251     if not os.path.isdir(directory):
252         try:
253             os.makedirs(directory)
254         except OSError:
255             pass
256
257
258 def copy_grml_files(grml_flavour, iso_mount, target):
259     """Copy files from ISO on given target"""
260
261     # TODO:
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?
266
267     squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
268     squashfs_target = target + '/live/'
269     mkdir(squashfs_target)
270
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"])
274
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'])
278
279     release_target = target + '/boot/release/' + grml_flavour
280     mkdir(release_target)
281
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'])
285
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'])
289
290     isolinux_target = target + '/boot/isolinux/'
291     mkdir(isolinux_target)
292
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'])
296
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])
301
302     grub_target = target + '/boot/grub/'
303     mkdir(grub_target)
304
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'])
307
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'])
310
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( )
315
316     syslinux_target = target + '/boot/isolinux/'
317     mkdir(syslinux_target)
318
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( )
323
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( )
328
329
330 def uninstall_files(device):
331     """Get rid of all grml files on specified device"""
332
333     print("TODO")
334
335
336 def identify_grml_flavour(mountpath):
337     """Get name of grml flavour"""
338
339     version_file = search_file('grml-version', mountpath)
340     file = open(version_file, 'r')
341     grml_info = file.readline()
342     file.close
343     grml_flavour = re.match(r'[\w-]*', grml_info).group()
344     return grml_flavour
345
346
347 def main():
348     if options.version:
349         print("%s %s")% (os.path.basename(sys.argv[0]), prog_version)
350         sys.exit(0)
351
352     if len(args) < 2:
353         parser.error("invalid usage")
354
355     # check_uid_root()
356
357     device = args[len(args) - 1]
358     isos = args[0:len(args) - 1]
359
360     if not which("syslinux"):
361         print("Sorry, syslinux not available. Exiting.")
362         print("Please install syslinux or consider using the --grub option.")
363         sys.exit(1)
364
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)
369
370     # FIXME
371     target = '/mnt/usb-sdb1'
372
373     # TODO it doesn't need to be a ISO, could be /live/image as well
374     for iso in isos:
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
380
381         grml_flavour = identify_grml_flavour(iso_mount)
382         print("debug: grml_flavour = %s") % grml_flavour
383
384         grml_flavour_short = grml_flavour.replace('-','')
385         print("debug: grml_flavour_short = %s") % grml_flavour_short
386
387         copy_grml_files(grml_flavour, iso_mount, target)
388
389
390     if options.mbr:
391         print("debug: would install MBR now")
392
393     install_bootloader(device)
394
395 if __name__ == "__main__":
396     main()
397
398 ## END OF FILE #################################################################
399 # vim:foldmethod=marker expandtab ai ft=python tw=120