3ef8e4218062babb3d19c96add002d02bb357e3c
[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 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")
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         # TODO: actual execution ;)
74         print "executing %s" % command
75
76 def which(program):
77     def is_exe(fpath):
78         return os.path.exists(fpath) and os.access(fpath, os.X_OK)
79
80     fpath, fname = os.path.split(program)
81     if fpath:
82         if is_exe(program):
83             return program
84     else:
85         for path in os.environ["PATH"].split(os.pathsep):
86             exe_file = os.path.join(path, program)
87             if is_exe(exe_file):
88                 return exe_file
89
90     return None
91
92 def search_file(filename, search_path='/bin' + pathsep + '/usr/bin'):
93    """Given a search path, find file"""
94    file_found = 0
95    paths = split(search_path, pathsep)
96    for path in paths:
97        for current_dir, directories, files in os.walk(path):
98            if exists(join(current_dir, filename)):
99               file_found = 1
100               break
101    if file_found:
102       return abspath(join(current_dir, filename))
103    else:
104       return None
105 # }}}
106
107
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).")
112
113
114 def install_syslinux(device):
115     """Install syslinux on specified device."""
116     print("debug: syslinux %s [TODO]") % device
117
118
119 def generate_grub_config(grml_flavour):
120     """Generate grub configuration for use via menu,lst"""
121
122     # TODO:
123     # * what about system using grub2 without having grub available?
124     # * support grub2
125
126     grml_name = grml_flavour
127
128     return("""\
129 # misc options:
130 timeout 30
131 # color red/blue green/black
132 splashimage=/boot/grub/splash.xpm.gz
133 foreground  = 000000
134 background  = FFCC33
135
136 # define entries:
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
140
141 # TODO: extend configuration :)
142 """ % locals())
143
144
145 def generate_isolinux_splash(grml_flavour):
146     """Generate bootsplash for isolinux/syslinux"""
147
148     # TODO:
149     # * adjust last bootsplash line
150
151     grml_name = grml_flavour
152
153     return("""\
154 \ f17\f\18/boot/isolinux/logo.16
155
156 Some information and boot options available via keys F2 - F10. http://grml.org/
157 %(grml_name)s
158 """ % locals())
159
160 def generate_syslinux_config(grml_flavour):
161     """Generate configuration for use in syslinux.cfg"""
162
163     # TODO:
164     # * unify isolinux and syslinux setup ("INCLUDE /boot/...")
165
166     grml_name = grml_flavour
167
168     return("""\
169 # use this to control the bootup via a serial port
170 # SERIAL 0 9600
171 DEFAULT grml
172 TIMEOUT 300
173 PROMPT 1
174 DISPLAY /boot/isolinux/boot.msg
175 F1 /boot/isolinux/boot.msg
176 F2 /boot/isolinux/f2
177 F3 /boot/isolinux/f3
178 F4 /boot/isolinux/f4
179 F5 /boot/isolinux/f5
180 F6 /boot/isolinux/f6
181 F7 /boot/isolinux/f7
182 F8 /boot/isolinux/f8
183 F9 /boot/isolinux/f9
184 F10 /boot/isolinux/f10
185
186 LABEL grml
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
189
190 # TODO: extend configuration :)
191 """ % locals())
192
193
194 def install_grub(device):
195     """Install grub on specified device."""
196     print("grub-install %s") % device
197
198
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)
204     else:
205         device = partition
206
207     if options.grub:
208         install_grub(device)
209     else:
210         install_syslinux(device)
211
212
213 def install_mbr(target):
214     """Install a default master boot record on given target"""
215     print("TODO")
216
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
222
223 def loopback_mount(iso, target):
224     """Loopback mount specified ISO on given target"""
225
226     print("mount -o loop %s %s") % (iso, target)
227
228
229 def check_for_vat(partition):
230     """Check whether specified partition is VFAT/FAT16 filesystem"""
231
232     try:
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()
236
237         if udev_info.returncode == 2:
238             print("failed to read device %s - wrong UID / permissions?") % partition
239             return 1
240
241         if filesystem != "vfat":
242             return(1)
243
244         # TODO: check for ID_FS_VERSION=FAT16 as well?
245
246     except OSError:
247         print("Sorry, /lib/udev/vol_id not available.")
248         return 1
249
250 def mkdir(directory):
251     """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
252     if not os.path.isdir(directory):
253         try:
254             os.makedirs(directory)
255         except OSError:
256             pass
257
258
259 def copy_grml_files(grml_flavour, iso_mount, target):
260     """Copy files from ISO on given target"""
261
262     # TODO:
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?
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     (options, args) = parser.parse_args()
349
350     if options.version:
351         print("%s %s")% (os.path.basename(sys.argv[0]), prog_version)
352         sys.exit(0)
353
354     if len(args) < 2:
355         parser.error("invalid usage")
356
357     # check_uid_root()
358
359     device = args[len(args) - 1]
360     isos = args[0:len(args) - 1]
361
362     if not which("syslinux"):
363         print("Sorry, syslinux not available. Exiting.")
364         print("Please install syslinux or consider using the --grub option.")
365         sys.exit(1)
366
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)
371
372     # FIXME
373     target = '/mnt/usb-sdb1'
374
375     # TODO it doesn't need to be a ISO, could be /live/image as well
376     for iso in isos:
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
382
383         grml_flavour = identify_grml_flavour(iso_mount)
384         print("debug: grml_flavour = %s") % grml_flavour
385
386         grml_flavour_short = grml_flavour.replace('-','')
387         print("debug: grml_flavour_short = %s") % grml_flavour_short
388
389         copy_grml_files(grml_flavour, iso_mount, target)
390
391
392     if options.mbr:
393         print("debug: would install MBR now")
394
395     install_bootloader(device)
396
397 if __name__ == "__main__":
398     main()
399
400 ## END OF FILE #################################################################
401 # vim:foldmethod=marker expandtab ai ft=python tw=120