Implement prototype of copy_grml_files(), move f# files to isolinux directory again
[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 # * write error messages to stderr
11 # * log wrapper (log important messages to syslog, depending on loglevel)
12 # * trap handling (umount devices when interrupting?)
13 # * integrate https://www.mirbsd.org/cvs.cgi/src/sys/arch/i386/stand/mbr/mbr.S?rev=HEAD;content-type=text%2Fplain
14 #   -> gcc -D_ASM_SOURCE  -D__BOOT_VER=\"GRML\" -DBOOTMANAGER -c mbr.S; ld
15 #      -nostdlib -Ttext 0 -N -Bstatic --oformat binary mbr.o -o mbrmgr
16
17 prog_version = "0.0.1"
18
19 import os, re, subprocess, sys
20 from optparse import OptionParser
21 from os.path import exists, join, abspath
22 from os import pathsep
23 from string import split
24
25 # cmdline parsing {{{
26 usage = "Usage: %prog [options] <ISO[s]> <partition>\n\
27 \n\
28 %prog installs a grml ISO to an USB device to be able to boot from it.\n\
29 Make sure you have at least a grml ISO or a running grml system,\n\
30 syslinux (just run 'aptitude install syslinux' on Debian-based systems)\n\
31 and root access."
32 parser = OptionParser(usage=usage)
33
34 parser.add_option("--bootoptions", dest="bootoptions", action="store", type="string",
35                   help="use specified bootoptions as defaut")
36 parser.add_option("--dry-run", dest="dryrun", action="store_true",
37                   help="do not actually execute any commands")
38 parser.add_option("--fat16", dest="fat16", action="store_true",
39                   help="format specified partition with FAT16")
40 parser.add_option("--force", dest="force", action="store_true",
41                   help="force any actions requiring manual interaction")
42 parser.add_option("--grub", dest="grub", action="store_true",
43                   help="install grub bootloader instead of syslinux")
44 parser.add_option("--initrd", dest="initrd", action="store", type="string",
45                   help="install specified initrd instead of the default")
46 parser.add_option("--kernel", dest="kernel", action="store", type="string",
47                   help="install specified kernel instead of the default")
48 parser.add_option("--mbr", dest="mbr", action="store_true",
49                   help="install master boot record (MBR) on the device")
50 parser.add_option("--squashfs", dest="squashfs", action="store", type="string",
51                   help="install specified squashfs file instead of the default")
52 parser.add_option("--uninstall", dest="uninstall", action="store_true",
53                   help="remove grml ISO files")
54 parser.add_option("--verbose", dest="verbose", action="store_true",
55                   help="enable verbose mode")
56 parser.add_option("-v", "--version", dest="version", action="store_true",
57                   help="display version and exit")
58
59 (options, args) = parser.parse_args()
60 # }}}
61
62 # wrapper functions {{{
63 # TODO: implement argument handling
64 def execute(command):
65     """Wrapper for executing a command. Either really executes
66     the command (default) or when using --dry-run commandline option
67     just displays what would be executed."""
68     if options.dryrun:
69         print "would execute %s now" % command
70     else:
71         print "executing %s" % command
72
73 def which(program):
74     def is_exe(fpath):
75         return os.path.exists(fpath) and os.access(fpath, os.X_OK)
76
77     fpath, fname = os.path.split(program)
78     if fpath:
79         if is_exe(program):
80             return program
81     else:
82         for path in os.environ["PATH"].split(os.pathsep):
83             exe_file = os.path.join(path, program)
84             if is_exe(exe_file):
85                 return exe_file
86
87     return None
88
89 def search_file(filename, search_path='/bin' + pathsep + '/usr/bin'):
90    """Given a search path, find file"""
91    file_found = 0
92    paths = split(search_path, pathsep)
93    for path in paths:
94        for current_dir, directories, files in os.walk(path):
95            if exists(join(current_dir, filename)):
96               file_found = 1
97               break
98    if file_found:
99       return abspath(join(current_dir, filename))
100    else:
101       return None
102 # }}}
103
104
105 def check_uid_root():
106     """Check for root permissions"""
107     if not os.geteuid()==0:
108         sys.exit("Error: please run this script with uid 0 (root).")
109
110
111 def install_syslinux(device):
112     """Install syslinux on specified device."""
113     print("debug: syslinux %s") % device
114
115
116 def install_grub(device):
117     """Install grub on specified device."""
118     print("grub-install %s") % device
119
120
121 def install_bootloader(partition):
122     """Install bootloader on device."""
123     # Install bootloader on the device (/dev/sda), not on the partition itself (/dev/sda1)
124     if partition[-1:].isdigit():
125         device = re.match(r'(.*?)\d*$', partition).group(1)
126     else:
127         device = partition
128
129     if options.grub:
130         install_grub(device)
131     else:
132         install_syslinux(device)
133
134
135 def install_mbr(target):
136     """Install a default master boot record on given target"""
137     print("TODO")
138
139
140 def loopback_mount(iso, target):
141     """Loopback mount specified ISO on given target"""
142     print("mount -o loop %s %s") % (iso, target)
143
144
145 def check_for_vat(partition):
146     """Check whether specified partition is VFAT/FAT16 filesystem"""
147     try:
148         udev_info = subprocess.Popen(["/lib/udev/vol_id", "-t",
149             partition],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
150         filesystem = udev_info.communicate()[0].rstrip()
151
152         if udev_info.returncode == 2:
153             print("failed to read device %s - wrong UID / permissions?") % partition
154             return 1
155
156         if filesystem != "vfat":
157             return(1)
158
159         # TODO: check for ID_FS_VERSION=FAT16?
160
161     except OSError:
162         print("Sorry, /lib/udev/vol_id not available.")
163         return 1
164
165 def copy_grml_files(grml_flavour, iso_mount, target):
166     """Copy files from ISO on given target"""
167
168     # TODO: provide alternative search_file() if file information is stored in
169     # a config.ini file?
170     squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
171     print("debug: copy squashfs to %s") % target + '/live/' + grml_flavour + '.squashfs'
172
173     filesystem_module = search_file('filesystem.module', iso_mount)
174     print("debug: copy filesystem.module to %s") % target + '/live/' + grml_flavour + '.module'
175
176     kernel = search_file('linux26', iso_mount)
177     print("debug: copy kernel to %s") % target + '/boot/release/' + grml_flavour + '/linux26'
178
179     initrd = search_file('initrd.gz', iso_mount)
180     print("debug: copy initrd to %s") % target + '/boot/release/' + grml_flavour + '/initrd.gz'
181
182     logo = search_file('logo.16', iso_mount)
183     print("debug: copy logo.16 to %s") % target + '/boot/isolinux/' + 'logo.16'
184
185     for file in 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10':
186         bootsplash = search_file(file, iso_mount)
187         print("debug: copy %s to %s") % (bootsplash, target + '/boot/isolinux/' + file)
188
189
190 def uninstall_files(device):
191     print("TODO")
192
193
194 def identify_grml_flavour(mountpath):
195     version_file = search_file('grml-version', mountpath)
196     file = open(version_file, 'r')
197     grml_info = file.readline()
198     file.close
199     grml_flavour = re.match(r'[\w-]*', grml_info).group()
200     return grml_flavour
201
202
203 def main():
204     if options.version:
205         print("%s %s")% (os.path.basename(sys.argv[0]), prog_version)
206         sys.exit(0)
207
208     if len(args) < 2:
209         parser.error("invalid usage")
210
211     # check_uid_root()
212
213     device = args[len(args) - 1]
214     isos = args[0:len(args) - 1]
215
216     if not which("syslinux"):
217         print("Sorry, syslinux not available. Exiting.")
218         print("Please install syslinux or consider using the --grub option.")
219         sys.exit(1)
220
221     # TODO check for valid blockdevice, vfat and mount functions
222     # if device is not None:
223         # check_for_vat(device)
224         # mount_target(partition)
225
226     target = '/mnt/target'
227
228     # TODO it doesn't need to be a ISO, could be /live/image as well
229     for iso in isos:
230         print("debug: iso = %s") % iso
231         # loopback_mount(iso)
232         # copy_grml_files(iso, target)
233         # loopback_unmount(iso)
234         iso_mount = '/mnt/test' # FIXME
235
236         grml_flavour = identify_grml_flavour(iso_mount)
237         print("debug: grml_flavour = %s") % grml_flavour
238
239         grml_flavour_short = grml_flavour.replace('-','')
240         print("debug: grml_flavour_short = %s") % grml_flavour_short
241
242         copy_grml_files(grml_flavour, iso_mount, target)
243
244     if options.mbr:
245         print("debug: would install MBR now")
246
247     install_bootloader(device)
248
249 if __name__ == "__main__":
250     main()
251
252 ## END OF FILE #################################################################
253 # vim:foldmethod=marker expandtab ai ft=python tw=120