Implement search_file()
[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):
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
106 def check_uid_root():
107     """Check for root permissions"""
108     if not os.geteuid()==0:
109         sys.exit("Error: please run this script with uid 0 (root).")
110
111
112 def install_syslinux(device):
113     """Install syslinux on specified device."""
114     print("syslinux %s") % device
115
116
117 def install_grub(device):
118     """Install grub on specified device."""
119     print("grub-install %s") % device
120
121
122 def install_bootloader(partition):
123     """Install bootloader on device."""
124     # Install bootloader on the device (/dev/sda), not on the partition itself (/dev/sda1)
125     if partition[-1:].isdigit():
126         device = re.match(r'(.*?)\d*$', partition).group(1)
127     else:
128         device = partition
129
130     if options.grub:
131         install_grub(device)
132     else:
133         install_syslinux(device)
134
135
136 def install_mbr(target):
137     """Install a default master boot record on given target"""
138     print("TODO")
139
140
141 def loopback_mount(iso, target):
142     """Loopback mount specified ISO on given target"""
143     print("mount -o loop %s %s") % (iso, target)
144
145
146 def check_for_vat(partition):
147     """Check whether specified partition is VFAT/FAT16 filesystem"""
148     try:
149         udev_info = subprocess.Popen(["/lib/udev/vol_id", "-t",
150             partition],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
151         filesystem = udev_info.communicate()[0].rstrip()
152
153         if udev_info.returncode == 2:
154             print("failed to read device %s - wrong UID / permissions?") % partition
155             return 1
156
157         if filesystem != "vfat":
158             return(1)
159
160         # TODO: check for ID_FS_VERSION=FAT16?
161
162     except OSError:
163         print("Sorry, /lib/udev/vol_id not available.")
164         return 1
165
166 def copy_grml_files(target):
167     """Copy files from ISO on given target"""
168     print("TODO")
169
170
171 def uninstall_files(device):
172     print("TODO")
173
174
175 def main():
176     if options.version:
177         print("%s %s")% (os.path.basename(sys.argv[0]), prog_version)
178         sys.exit(0)
179
180     if len(args) < 2:
181         parser.error("invalid usage")
182
183     # check_uid_root()
184
185     device = args[len(args) - 1]
186     isos = args[0:len(args) - 1]
187
188     if not which("syslinux"):
189         print("Sorry, syslinux not available. Exiting.")
190         print("Please install syslinux or consider using the --grub option.")
191         sys.exit(1)
192
193     # TODO check for valid blockdevice, vfat and mount functions
194     # if device is not None:
195         # check_for_vat(device)
196         # mount_target(partition)
197
198     # TODO it doesn't need to be a ISO, could be /live/image as well
199     for iso in isos:
200         print("iso = %s") % iso
201         # loopback_mount(iso)
202         # copy_grml_files(iso, target)
203         # loopback_unmount(iso)
204
205     search_path = '/bin' + pathsep + '/usr/bin'
206     find_file = search_file('grml-medium.squashfs', '/mnt/test')
207     print("find_file = %s") % find_file
208
209     if options.mbr:
210         print("would install MBR now")
211
212     install_bootloader(device)
213
214 if __name__ == "__main__":
215     main()
216
217 ## END OF FILE #################################################################
218 # vim:foldmethod=marker expandtab ai ft=python