8097a83dcb90805f82d97ce1cc0ede2692c1d4ba
[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
14 prog_version = "0.0.1"
15
16 import os, re, subprocess, sys
17 from optparse import OptionParser
18
19 # cmdline parsing {{{
20 usage = "Usage: %prog [options] <ISO[s]> <partition>\n\
21 \n\
22 %prog installs a grml ISO to an USB device to be able to boot from it.\n\
23 Make sure you have at least a grml ISO or a running grml system,\n\
24 syslinux (just run 'aptitude install syslinux' on Debian-based systems)\n\
25 and root access."
26 parser = OptionParser(usage=usage)
27
28 parser.add_option("--bootoptions", dest="bootoptions", action="store", type="string",
29                   help="use specified bootoptions as defaut")
30 parser.add_option("--dry-run", dest="dryrun", action="store_true",
31                   help="do not actually execute any commands")
32 parser.add_option("--fat16", dest="fat16", action="store_true",
33                   help="format specified partition with FAT16")
34 parser.add_option("--force", dest="force", action="store_true",
35                   help="force any actions requiring manual interaction")
36 parser.add_option("--grub", dest="grub", action="store_true",
37                   help="install grub bootloader instead of syslinux")
38 parser.add_option("--initrd", dest="initrd", action="store", type="string",
39                   help="install specified initrd instead of the default")
40 parser.add_option("--kernel", dest="kernel", action="store", type="string",
41                   help="install specified kernel instead of the default")
42 parser.add_option("--mbr", dest="mbr", action="store_true",
43                   help="install master boot record (MBR) on the device")
44 parser.add_option("--squashfs", dest="squashfs", action="store", type="string",
45                   help="install specified squashfs file instead of the default")
46 parser.add_option("--uninstall", dest="uninstall", action="store_true",
47                   help="remove grml ISO files")
48 parser.add_option("--verbose", dest="verbose", action="store_true",
49                   help="enable verbose mode")
50 parser.add_option("-v", "--version", dest="version", action="store_true",
51                   help="display version and exit")
52
53 (options, args) = parser.parse_args()
54 # }}}
55
56 # wrapper functions {{{
57 # TODO: implement argument handling
58 def execute(command):
59     """Wrapper for executing a command. Either really executes
60     the command (default) or when using --dry-run commandline option
61     just displays what would be executed."""
62     if options.dryrun:
63         print "would execute %s now" % command
64     else:
65         print "executing %s" % command
66
67 def which(program):
68     def is_exe(fpath):
69         return os.path.exists(fpath) and os.access(fpath, os.X_OK)
70
71     fpath, fname = os.path.split(program)
72     if fpath:
73         if is_exe(program):
74             return program
75     else:
76         for path in os.environ["PATH"].split(os.pathsep):
77             exe_file = os.path.join(path, program)
78             if is_exe(exe_file):
79                 return exe_file
80
81     return None
82 # }}}
83
84
85 def check_uid_root():
86     """Check for root permissions"""
87     if not os.geteuid()==0:
88         sys.exit("Error: please run this script with uid 0 (root).")
89
90
91 def install_syslinux(device):
92     """Install syslinux on specified device."""
93     print("syslinux %s") % device
94
95
96 def install_grub(device):
97     """Install grub on specified device."""
98     print("grub-install %s") % device
99
100
101 def install_bootloader(partition):
102     """Install bootloader on device."""
103     # Install bootloader on the device (/dev/sda), not on the partition itself (/dev/sda1)
104     if partition[-1:].isdigit():
105         device = re.match(r'(.*?)\d*$', partition).group(1)
106     else:
107         device = partition
108
109     if options.grub:
110         install_grub(device)
111     else:
112         install_syslinux(device)
113
114
115 def install_mbr(target):
116     """Install a default master boot record on given target"""
117     print("TODO")
118
119
120 def loopback_mount(iso, target):
121     """Loopback mount specified ISO on given target"""
122     print("mount -o loop %s %s") % (iso, target)
123
124
125 def check_for_vat(partition):
126     """Check whether specified partition is VFAT/FAT16 filesystem"""
127     try:
128         udev_info = subprocess.Popen(["/lib/udev/vol_id", "-t",
129             partition],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
130         filesystem = udev_info.communicate()[0].rstrip()
131
132         if udev_info.returncode == 2:
133             print("failed to read device %s - wrong UID / permissions?") % partition
134             return 1
135
136         if filesystem != "vfat":
137             return(1)
138
139         # TODO: check for ID_FS_VERSION=FAT16?
140
141     except OSError:
142         print("Sorry, /lib/udev/vol_id not available.")
143         return 1
144
145 def copy_grml_files(target):
146     """Copy files from ISO on given target"""
147     print("TODO")
148
149
150 def uninstall_files(device):
151     print("TODO")
152
153
154 def main():
155     if options.version:
156         print("%s %s")% (os.path.basename(sys.argv[0]), prog_version)
157         sys.exit(0)
158
159     if len(args) < 2:
160         parser.error("invalid usage")
161
162     # check_uid_root()
163
164     device = args[len(args) - 1]
165     isos = args[0:len(args) - 1]
166
167     if not which("syslinux2"):
168         print("Sorry, syslinux not available. Exiting.")
169         print("Please install syslinux or consider using the --grub option.")
170         sys.exit(1)
171     
172     # TODO check for valid blockdevice, vfat and mount functions
173     # if device is not None:
174         # check_for_vat(device)
175         # mount_target(partition)
176
177     # TODO it doesn't need to be a ISO, could be /live/image as well!
178     for iso in isos:
179         print("iso = %s") % iso
180         # loopback_mount(iso)
181         # copy_grml_files(iso, target)
182         # loopback_unmount(iso)
183
184     if options.mbr:
185         print("would install MBR now")
186
187     install_bootloader(device)
188
189 if __name__ == "__main__":
190     main()
191
192 ## END OF FILE #################################################################
193 # vim:foldmethod=marker expandtab ai ft=python