+ except OSError:
+ raise CriticalException("Sorry, /sbin/blkid not available (install e2fsprogs?)")
+
+
+def mkdir(directory):
+ """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
+
+ # just silently pass as it's just fine it the directory exists
+ if not os.path.isdir(directory):
+ try:
+ os.makedirs(directory)
+ # pylint: disable-msg=W0704
+ except OSError:
+ pass
+
+
+def exec_rsync(source, target):
+ """Simple wrapper around rsync to install files
+
+ @source: source file/directory
+ @target: target file/directory"""
+ logging.debug("Source: %s / Target: %s", source, target)
+ proc = subprocess.Popen(["rsync", "-rlptDH", "--inplace", source, target])
+ proc.wait()
+ if proc.returncode == 12:
+ logging.critical("Fatal: No space left on device")
+ cleanup()
+ sys.exit(1)
+
+ if proc.returncode != 0:
+ logging.critical("Fatal: could not install %s", source)
+ cleanup()
+ sys.exit(1)
+
+
+def write_uuid(target_file):
+ """Generates an returns uuid and write it to the specified file
+
+ @target_file: filename to write the uuid to
+ """
+
+ fileh = open(target_file, 'w')
+ uid = str(uuid.uuid4())
+ fileh.write(uid)
+ fileh.close()
+ return uid
+
+
+def get_uuid(target):
+ """Get the uuid of the specified target. Will generate an uuid if none exist.
+
+ @target: directory/mountpoint containing the grml layout
+ """
+
+ conf_target = target + "/conf/"
+ uuid_file_name = conf_target + "/bootid.txt"
+ if os.path.isdir(conf_target):
+ if os.path.isfile(uuid_file_name):
+ uuid_file = open(uuid_file_name, 'r')
+ uid = uuid_file.readline().strip()
+ uuid_file.close()
+ return uid
+ else:
+ return write_uuid(uuid_file_name)
+ else:
+ execute(mkdir, conf_target)
+ return write_uuid(uuid_file_name)
+
+
+def copy_system_files(grml_flavour, iso_mount, target):
+ """copy grml's main files (like squashfs, kernel and initrd) to a given target
+
+ @grml_flavour: name of grml flavour the configuration should be generated for
+ @iso_mount: path where a grml ISO is mounted on
+ @target: path where grml's main files should be copied to"""
+
+ squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
+ if squashfs is None:
+ logging.critical("Fatal: squashfs file not found"
+ ", please check that your iso is not corrupt")
+ raise CriticalException("error locating squashfs file")
+ else:
+ squashfs_target = target + '/live/' + grml_flavour + '/'
+ execute(mkdir, squashfs_target)
+ exec_rsync(squashfs, squashfs_target + grml_flavour + '.squashfs')
+
+ for prefix in grml_flavour + "/", "":
+ filesystem_module = search_file(prefix + 'filesystem.module', iso_mount)
+ if filesystem_module:
+ break
+ if filesystem_module is None:
+ logging.critical("Fatal: filesystem.module not found")
+ raise CriticalException("error locating filesystem.module file")
+ else:
+ exec_rsync(filesystem_module, squashfs_target + 'filesystem.module')
+
+
+ release_path = 'boot/release/' + grml_flavour.replace('-', '')
+ release_target = target + "/" + release_path
+ execute(mkdir, release_target)
+
+ prefix = ""
+ if os.path.isdir(iso_mount + '/boot/release'):
+ prefix = release_path + '/'
+
+ kernel = search_file(prefix + 'linux26', iso_mount)
+ if kernel is None:
+ logging.critical("Fatal kernel not found")
+ raise CriticalException("error locating kernel file")
+ else:
+ exec_rsync(kernel, release_target + '/linux26')
+
+ initrd = search_file(prefix + 'initrd.gz', iso_mount)
+ if initrd is None:
+ logging.critical("Fatal: initrd not found")
+ raise CriticalException("error locating initrd file")
+ else:
+ exec_rsync(initrd, release_target + '/initrd.gz')
+
+
+def update_grml_versions(iso_mount, target):
+ """Update the grml version file on a cd
+ Returns true if version was updated successfully,
+ False if grml-version does not exist yet on the mountpoint
+
+ @iso_mount: string of the iso mount point
+ @target: path of the target mount point
+ """
+ grml_target = target + '/grml/'
+ target_grml_version_file = search_file('grml-version', grml_target)
+ if target_grml_version_file:
+ iso_grml_version_file = search_file('grml-version', iso_mount)
+ if not iso_grml_version_file:
+ logging.warn("Warning: %s could not be found - can not install it", iso_grml_version_file)
+ return False
+ try:
+ # read the flavours from the iso image
+ iso_versions = {}
+ iso_file = open(iso_grml_version_file, 'r')
+ for line in iso_file:
+ iso_versions[get_flavour(line)] = line.strip()
+
+ # update the existing flavours on the target
+ for line in fileinput.input([target_grml_version_file], inplace=1):
+ flavour = get_flavour(line)
+ if flavour in iso_versions.keys():
+ print iso_versions.pop(flavour)
+ else:
+ print line.strip()
+ fileinput.close()
+
+ target_file = open(target_grml_version_file, 'a')
+ # add the new flavours from the current iso
+ for flavour in iso_versions:
+ target_file.write("%s\n" % iso_versions[flavour])
+ except IOError:
+ logging.warn("Warning: Could not write file")
+ finally:
+ iso_file.close()
+ target_file.close()
+ return True
+ else:
+ return False
+
+def copy_grml_files(iso_mount, target):
+ """copy some minor grml files to a given target
+
+ @iso_mount: path where a grml ISO is mounted on
+ @target: path where grml's main files should be copied to"""
+
+ grml_target = target + '/grml/'
+ execute(mkdir, grml_target)
+
+ copy_files = [ 'grml-cheatcodes.txt', 'LICENSE.txt', 'md5sums', 'README.txt' ]
+ # handle grml-version
+ if not update_grml_versions(iso_mount, target):
+ copy_files.append('grml-version')
+
+ for myfile in copy_files:
+ grml_file = search_file(myfile, iso_mount)
+ if grml_file is None:
+ logging.warn("Warning: file %s could not be found - can not install it", myfile)
+ else:
+ exec_rsync(grml_file, grml_target + myfile)
+
+ grml_web_target = grml_target + '/web/'
+ execute(mkdir, grml_web_target)
+
+ for myfile in 'index.html', 'style.css':
+ grml_file = search_file(myfile, iso_mount)
+ if grml_file is None:
+ logging.warn("Warning: file %s could not be found - can not install it", myfile)
+ else:
+ exec_rsync(grml_file, grml_web_target + myfile)
+
+ grml_webimg_target = grml_web_target + '/images/'
+ execute(mkdir, grml_webimg_target)
+
+ for myfile in 'button.png', 'favicon.png', 'linux.jpg', 'logo.png':
+ grml_file = search_file(myfile, iso_mount)
+ if grml_file is None:
+ logging.warn("Warning: file %s could not be found - can not install it", myfile)
+ else:
+ exec_rsync(grml_file, grml_webimg_target + myfile)
+
+
+def handle_addon_copy(filename, dst, iso_mount, ignore_errors=False):
+ """handle copy of optional addons
+
+ @filename: filename of the addon
+ @dst: destination directory
+ @iso_mount: location of the iso mount
+ @ignore_errors: don't report missing files
+ """
+ file_location = search_file(filename, iso_mount)
+ if file_location is None:
+ if not ignore_errors:
+ logging.warn("Warning: %s not found (that's fine if you don't need it)", filename)
+ else:
+ exec_rsync(file_location, dst)
+
+
+def copy_addons(iso_mount, target):
+ """copy grml's addons files (like allinoneimg, bsd4grml,..) to a given target
+
+ @iso_mount: path where a grml ISO is mounted on
+ @target: path where grml's main files should be copied to"""
+
+ addons = target + '/boot/addons/'
+ execute(mkdir, addons)
+
+ # grub all-in-one image
+ handle_addon_copy('allinone.img', addons, iso_mount)
+
+ # bsd imag
+ handle_addon_copy('bsd4grml', addons, iso_mount)
+
+ handle_addon_copy('balder10.imz', addons, iso_mount)
+
+ # install hdt and pci.ids only when using syslinux (grub doesn't support it)
+ if options.syslinux:
+ # hdt (hardware detection tool) image
+ hdtimg = search_file('hdt.c32', iso_mount)
+ if hdtimg:
+ exec_rsync(hdtimg, addons + '/hdt.c32')
+
+ # pci.ids file
+ picids = search_file('pci.ids', iso_mount)
+ if picids:
+ exec_rsync(picids, addons + '/pci.ids')
+
+ # memdisk image
+ handle_addon_copy('memdisk', addons, iso_mount)
+
+ # memtest86+ image
+ handle_addon_copy('memtest', addons, iso_mount)
+
+ # gpxe.lkrn: got replaced by ipxe
+ handle_addon_copy('gpxe.lkrn', addons, iso_mount, ignore_errors=True)
+
+ # ipxe.lkrn
+ handle_addon_copy('ipxe.lkrn', addons, iso_mount)
+
+def glob_and_copy(filepattern, dst):
+ """Glob on specified filepattern and copy the result to dst
+
+ @filepattern: globbing pattern
+ @dst: target directory
+ """
+ for name in glob.glob(filepattern):
+ copy_if_exist(name, dst)
+
+def search_and_copy(filename, search_path, dst):
+ """Search for the specified filename at searchpath and copy it to dst
+
+ @filename: filename to look for
+ @search_path: base search file
+ @dst: destionation to copy the file to
+ """
+ file_location = search_file(filename, search_path)
+ copy_if_exist(file_location, dst)
+
+def copy_if_exist(filename, dst):
+ """Copy filename to dst if filename is set.
+
+ @filename: a filename
+ @dst: dst file
+ """
+ if filename and (os.path.isfile(filename) or os.path.isdir(filename)):
+ exec_rsync(filename, dst)
+
+def copy_bootloader_files(iso_mount, target, grml_flavour):
+ """Copy grml's bootloader files to a given target
+
+ @iso_mount: path where a grml ISO is mounted on
+ @target: path where grml's main files should be copied to
+ @grml_flavour: name of the current processed grml_flavour
+ """
+
+ syslinux_target = target + '/boot/syslinux/'
+ execute(mkdir, syslinux_target)
+
+ grub_target = target + '/boot/grub/'
+ execute(mkdir, grub_target)
+
+ logo = search_file('logo.16', iso_mount)
+ exec_rsync(logo, syslinux_target + 'logo.16')
+
+ bootx64_efi = search_file('bootx64.efi', iso_mount)
+ if bootx64_efi:
+ mkdir(target + '/efi/boot/')
+ exec_rsync(bootx64_efi, target + '/efi/boot/bootx64.efi')
+
+ efi_img = search_file('efi.img', iso_mount)
+ if efi_img:
+ mkdir(target + '/boot/')
+ exec_rsync(efi_img, target + '/boot/efi.img')
+
+ for ffile in ['f%d' % number for number in range(1, 11) ]:
+ search_and_copy(ffile, iso_mount, syslinux_target + ffile)
+
+ loopback_cfg = search_file("loopback.cfg", iso_mount)
+ if loopback_cfg:
+ directory = os.path.dirname(loopback_cfg)
+ directory = directory.replace(iso_mount, "")
+ mkdir(os.path.join(target, directory))
+ exec_rsync(loopback_cfg, target + os.path.sep + directory)
+
+ # avoid the "file is read only, overwrite anyway (y/n) ?" question
+ # of mtools by syslinux ("mmove -D o -D O s:/ldlinux.sys $target_file")
+ if os.path.isfile(syslinux_target + 'ldlinux.sys'):
+ os.unlink(syslinux_target + 'ldlinux.sys')
+
+ (source_dir, name) = get_defaults_file(iso_mount, grml_flavour, "default.cfg")
+ (source_dir, defaults_file) = get_defaults_file(iso_mount, grml_flavour, "grml.cfg")
+
+ if not source_dir:
+ logging.critical("Fatal: file default.cfg could not be found.")
+ logging.critical("Note: this grml2usb version requires an ISO generated by grml-live >=0.9.24 ...")
+ logging.critical(" ... either use grml releases >=2009.10 or switch to an older grml2usb version.")
+ raise
+
+ for expr in name, 'distri.cfg', \
+ defaults_file, 'grml.png', 'hd.cfg', 'isolinux.cfg', 'isolinux.bin', \
+ 'isoprompt.cfg', 'options.cfg', \
+ 'prompt.cfg', 'vesamenu.cfg', 'grml.png', '*.c32':
+ glob_and_copy(iso_mount + source_dir + expr, syslinux_target)
+
+ for filename in glob.glob1(syslinux_target, "*.c32"):
+ copy_if_exist(os.path.join(SYSLINUX_LIBS, filename), syslinux_target)
+
+
+ # copy the addons_*.cfg file to the new syslinux directory
+ glob_and_copy(iso_mount + source_dir + 'addon*.cfg', syslinux_target)
+
+ search_and_copy('hidden.cfg', iso_mount + source_dir, syslinux_target + "new_" + 'hidden.cfg')
+
+
+ grub_target = target + '/boot/grub/'
+ execute(mkdir, grub_target)
+
+ if not os.path.isfile(GRML2USB_BASE + "/grub/splash.xpm.gz"):
+ logging.critical("Error: %s/grub/splash.xpm.gz can not be read.", GRML2USB_BASE)
+ logging.critical("Please make sure you've installed the grml2usb (Debian) package!")
+ raise
+ else:
+ exec_rsync(GRML2USB_BASE + '/grub/splash.xpm.gz', grub_target + 'splash.xpm.gz')
+
+ # grml splash in grub
+ copy_if_exist(GRML2USB_BASE + "/grub/grml.png", grub_target + 'grml.png')
+
+ # font file for graphical bootsplash in grub
+ copy_if_exist('/usr/share/grub/ascii.pf2', grub_target + 'ascii.pf2')
+
+ # always copy grub content as it might be useful
+
+ glob_and_copy(iso_mount + '/boot/grub/*.mod', grub_target)
+ glob_and_copy(iso_mount + '/boot/grub/*.img', grub_target)
+ glob_and_copy(iso_mount + '/boot/grub/stage*', grub_target)
+
+def install_iso_files(grml_flavour, iso_mount, device, target):
+ """Copy files from ISO to given target
+
+ @grml_flavour: name of grml flavour the configuration should be generated for
+ @iso_mount: path where a grml ISO is mounted on
+ @device: device/partition where bootloader should be installed to
+ @target: path where grml's main files should be copied to"""
+
+ global GRML_DEFAULT
+ GRML_DEFAULT = GRML_DEFAULT or grml_flavour
+ if options.dryrun:
+ return 0
+ elif not options.bootloaderonly:
+ logging.info("Copying files. This might take a while....")
+ try:
+ copy_system_files(grml_flavour, iso_mount, target)
+ copy_grml_files(iso_mount, target)
+ except CriticalException, error:
+ logging.critical("Execution failed: %s", error)
+ sys.exit(1)
+
+ if not options.skipaddons:
+ if not search_file('addons', iso_mount):
+ logging.info("Could not find addons, therefore not installing.")
+ else:
+ copy_addons(iso_mount, target)
+
+ if not options.copyonly:
+ copy_bootloader_files(iso_mount, target, grml_flavour)
+
+ if not options.dryrun:
+ handle_bootloader_config(grml_flavour, device, target)
+
+ # make sure we sync filesystems before returning
+ proc = subprocess.Popen(["sync"])
+ proc.wait()
+
+
+def get_flavour(flavour_str):
+ """Returns the flavour of a grml version string
+ """
+ return re.match(r'[\w-]*', flavour_str).group()
+
+def identify_grml_flavour(mountpath):
+ """Get name of grml flavour
+
+ @mountpath: path where the grml ISO is mounted to
+ @return: name of grml-flavour"""
+
+ version_file = search_file('grml-version', mountpath)
+
+ if version_file == "":
+ logging.critical("Error: could not find grml-version file.")
+ raise
+
+ flavours = []
+ tmpfile = None
+ try:
+ tmpfile = open(version_file, 'r')
+ for line in tmpfile.readlines():
+ flavours.append(get_flavour(line))
+ except TypeError, e:
+ raise
+ except Exception, e:
+ logging.critical("Unexpected error: %s", e)
+ raise
+ finally:
+ if tmpfile:
+ tmpfile.close()
+
+ return flavours
+
+
+def modify_grub_config(filename):
+ """Adjust bootoptions for a grub file
+
+ @filename: filename to modify
+ """
+ if options.removeoption:
+ regexe = []
+ for regex in options.removeoption:
+ regexe.append(re.compile(r'%s' % regex))
+
+ option_re = re.compile(r'(.*/boot/release/.*linux26.*)')
+
+ for line in fileinput.input(filename, inplace=1):
+ if regexe and option_re.search(line):
+ for regex in regexe:
+ line = regex.sub(' ', line)
+
+ sys.stdout.write(line)
+
+ fileinput.close()
+
+def handle_grub2_config(grml_flavour, grub_target, bootopt):
+ """Main handler for generating grub2 configuration
+
+ @grml_flavour: name of grml flavour the configuration should be generated for
+ @grub_target: path of grub's configuration files
+ @bootoptions: additional bootoptions that should be used by default"""
+
+ # grub2 config
+ grub2_cfg = grub_target + 'grub.cfg'
+ logging.debug("Creating grub2 configuration file (grub.cfg)")
+
+ global GRML_DEFAULT
+
+ # install main configuration only *once*, no matter how many ISOs we have:
+ grub_flavour_is_default = False
+ if os.path.isfile(grub2_cfg):
+ string = open(grub2_cfg).readline()
+ main_identifier = re.compile(".*main config generated at: %s.*" % re.escape(str(DATESTAMP)))
+ if not re.match(main_identifier, string):
+ grub2_config_file = open(grub2_cfg, 'w')
+ GRML_DEFAULT = grml_flavour
+ grub_flavour_is_default = True
+ grub2_config_file.write(generate_main_grub2_config(grml_flavour, bootopt))
+ grub2_config_file.close()
+ else:
+ grub2_config_file = open(grub2_cfg, 'w')
+ GRML_DEFAULT = grml_flavour
+ grub_flavour_is_default = True
+ grub2_config_file.write(generate_main_grub2_config(grml_flavour, bootopt))
+ grub2_config_file.close()
+
+ # install flavour specific configuration only *once* as well
+ grub_flavour_config = True
+ if os.path.isfile(grub2_cfg):
+ string = open(grub2_cfg).readlines()
+ flavour = re.compile("grml2usb for %s: %s" % (re.escape(grml_flavour), re.escape(str(DATESTAMP))))
+ for line in string:
+ if flavour.match(line):
+ grub_flavour_config = False
+
+ if grub_flavour_config:
+ grub2_config_file = open(grub2_cfg, 'a')
+ # display only if the grml flavour isn't the default
+ if not grub_flavour_is_default:
+ GRML_FLAVOURS.add(grml_flavour)
+ grub2_config_file.write(generate_flavour_specific_grub2_config(grml_flavour, bootopt))
+ grub2_config_file.close()
+
+ modify_grub_config(grub2_cfg)
+
+
+def get_bootoptions(grml_flavour):
+ """Returns bootoptions for specific flavour
+
+ @grml_flavour: name of the grml_flavour
+ """
+ # do NOT write "None" in kernel cmdline
+ if not options.bootoptions:
+ bootopt = ""
+ else:
+ bootopt = " ".join(options.bootoptions)
+ bootopt = bootopt.replace("%flavour", grml_flavour)
+ return bootopt
+
+
+def handle_grub_config(grml_flavour, device, target):
+ """Main handler for generating grub (v1 and v2) configuration
+
+ @grml_flavour: name of grml flavour the configuration should be generated for
+ @device: device/partition where grub should be installed to
+ @target: path of grub's configuration files"""
+
+ logging.debug("Generating grub configuration")
+
+ grub_target = target + '/boot/grub/'
+
+ bootopt = get_bootoptions(grml_flavour)
+
+ # write grub.cfg
+ handle_grub2_config(grml_flavour, grub_target, bootopt)
+
+
+def initial_syslinux_config(target):
+ """Generates intial syslinux configuration
+
+ @target path of syslinux's configuration files"""
+
+ target = target + "/"
+ filename = target + "grmlmain.cfg"
+ if os.path.isfile(target + "grmlmain.cfg"):
+ return
+ data = open(filename, "w")
+ data.write(generate_main_syslinux_config())
+ data.close()
+
+ filename = target + "hiddens.cfg"
+ data = open(filename, "w")
+ data.write("include hidden.cfg\n")
+ data.close()
+
+def add_entry_if_not_present(filename, entry):
+ """Write entry into filename if entry is not already in the file
+
+ @filanme: name of the file
+ @entry: data to write to the file
+ """
+ data = open(filename, "a+")
+ for line in data:
+ if line == entry:
+ break
+ else:
+ data.write(entry)
+
+ data.close()
+
+def get_flavour_filename(flavour):
+ """Generate a iso9960 save filename out of the specified flavour
+
+ @flavour: grml flavour
+ """
+ return flavour.replace('-', '_')
+
+def adjust_syslinux_bootoptions(src, flavour):
+ """Adjust existing bootoptions of specified syslinux config to
+ grml2usb specific ones, e.g. change the location of the kernel...
+
+ @src: config file to alter
+ @flavour: grml flavour
+ """
+
+ append_re = re.compile("^(\s*append.*/boot/release.*)$", re.I)
+ boot_re = re.compile("/boot/([a-zA-Z0-9_]+/)+([a-zA-Z0-9._]+)")
+ # flavour_re = re.compile("(label.*)(grml\w+)")
+ default_re = re.compile("(default.cfg)")
+ bootid_re = re.compile("bootid=[\w_-]+")
+ live_media_path_re = re.compile("live-media-path=[\w_/-]+")
+
+ bootopt = get_bootoptions(flavour)
+
+ regexe = []
+ option_re = None
+ if options.removeoption:
+ option_re = re.compile(r'/boot/release/.*/initrd.gz')
+
+ for regex in options.removeoption:
+ regexe.append(re.compile(r'%s' % regex))
+
+ for line in fileinput.input(src, inplace=1):
+ line = boot_re.sub(r'/boot/release/%s/\2 ' % flavour.replace('-', ''), line)
+ # line = flavour_re.sub(r'\1 %s-\2' % flavour, line)
+ line = default_re.sub(r'%s-\1' % flavour, line)
+ line = bootid_re.sub('', line)
+ line = live_media_path_re.sub('', line)
+ line = append_re.sub(r'\1 live-media-path=/live/%s/ ' % flavour, line)
+ line = append_re.sub(r'\1 boot=live %s ' % bootopt, line)
+ line = append_re.sub(r'\1 %s=%s ' % ("bootid", UUID), line)
+ if option_re and option_re.search(line):
+ for regex in regexe:
+ line = regex.sub(' ', line)
+ sys.stdout.write(line)
+ fileinput.close()
+
+def adjust_labels(src, replacement):
+ """Adjust the specified labels in the syslinux config file src with
+ specified replacement
+ """
+ label_re = re.compile("^(\s*label\s*) ([a-zA-Z0-9_-]+)", re.I)
+ for line in fileinput.input(src, inplace=1):
+ line = label_re.sub(replacement, line)
+ sys.stdout.write(line)
+ fileinput.close()
+
+
+def add_syslinux_entry(filename, grml_flavour):
+ """Add includes for a specific grml_flavour to the specified filename
+
+ @filename: syslinux config file
+ @grml_flavour: grml flavour to add
+ """
+
+ entry_filename = "option_%s.cfg" % grml_flavour
+ entry = "include %s\n" % entry_filename
+
+ add_entry_if_not_present(filename, entry)
+ path = os.path.dirname(filename)
+
+ data = open(path + "/" + entry_filename, "w")
+ data.write(generate_flavour_specific_syslinux_config(grml_flavour))
+ data.close()
+
+def modify_filenames(grml_flavour, target, filenames):
+ """Replace the standarf filenames with the new ones
+
+ @grml_flavour: grml-flavour strin
+ @target: directory where the files are located
+ @filenames: list of filenames to alter
+ """
+ grml_filename = grml_flavour.replace('-', '_')
+ for filename in filenames:
+ old_filename = "%s/%s" % (target, filename)
+ new_filename = "%s/%s_%s" % (target, grml_filename, filename)
+ os.rename(old_filename, new_filename)
+
+
+def remove_default_entry(filename):
+ """Remove the default entry from specified syslinux file
+
+ @filename: syslinux config file
+ """
+ default_re = re.compile("^(\s*menu\s*default\s*)$", re.I)
+ for line in fileinput.input(filename, inplace=1):
+ if default_re.match(line):
+ continue
+ sys.stdout.write(line)
+ fileinput.close()
+
+
+def handle_syslinux_config(grml_flavour, target):
+ """Main handler for generating syslinux configuration
+
+ @grml_flavour: name of grml flavour the configuration should be generated for
+ @target: path of syslinux's configuration files"""
+
+ logging.debug("Generating syslinux configuration")
+ syslinux_target = target + '/boot/syslinux/'
+ # should be present via copy_bootloader_files(), but make sure it exits:
+ execute(mkdir, syslinux_target)
+ syslinux_cfg = syslinux_target + 'syslinux.cfg'
+
+
+ # install main configuration only *once*, no matter how many ISOs we have:
+ syslinux_config_file = open(syslinux_cfg, 'w')
+ syslinux_config_file.write("TIMEOUT 300\n")
+ syslinux_config_file.write("include vesamenu.cfg\n")
+ syslinux_config_file.close()
+
+ prompt_name = open(syslinux_target + 'promptname.cfg', 'w')
+ prompt_name.write('menu label S^yslinux prompt\n')
+ prompt_name.close()
+
+ initial_syslinux_config(syslinux_target)
+ flavour_filename = grml_flavour.replace('-', '_')
+
+ if search_file('default.cfg', syslinux_target):
+ modify_filenames(grml_flavour, syslinux_target, ['grml.cfg', 'default.cfg'])
+
+ filename = search_file("new_hidden.cfg", syslinux_target)
+
+
+ # process hidden file
+ if not search_file("hidden.cfg", syslinux_target):
+ new_hidden = syslinux_target + "hidden.cfg"
+ os.rename(filename, new_hidden)
+ adjust_syslinux_bootoptions(new_hidden, grml_flavour)
+ else:
+ new_hidden_file = "%s/%s_hidden.cfg" % (syslinux_target, flavour_filename)
+ os.rename(filename, new_hidden_file)
+ adjust_labels(new_hidden_file, r'\1 %s-\2' % grml_flavour)
+ adjust_syslinux_bootoptions(new_hidden_file, grml_flavour)
+ entry = 'include %s_hidden.cfg\n' % flavour_filename
+ add_entry_if_not_present("%s/hiddens.cfg" % syslinux_target, entry)
+
+
+
+ new_default = "%s_default.cfg" % (flavour_filename)
+ entry = 'include %s\n' % new_default
+ defaults_file = '%s/defaults.cfg' % syslinux_target
+ new_default_with_path = "%s/%s" % (syslinux_target, new_default)
+ new_grml_cfg = "%s/%s_grml.cfg" % ( syslinux_target, flavour_filename)
+
+ if os.path.isfile(defaults_file):
+
+ # remove default menu entry in menu
+ remove_default_entry(new_default_with_path)
+
+ # adjust all labels for additional isos
+ adjust_labels(new_default_with_path, r'\1 %s' % grml_flavour)
+ adjust_labels(new_grml_cfg, r'\1 %s-\2' % grml_flavour)
+
+ # always adjust bootoptions
+ adjust_syslinux_bootoptions(new_default_with_path, grml_flavour)
+ adjust_syslinux_bootoptions(new_grml_cfg, grml_flavour)
+
+ add_entry_if_not_present("%s/defaults.cfg" % syslinux_target, entry)
+
+ add_syslinux_entry("%s/additional.cfg" % syslinux_target, flavour_filename)
+
+
+def handle_bootloader_config(grml_flavour, device, target):
+ """Main handler for generating bootloader's configuration
+
+ @grml_flavour: name of grml flavour the configuration should be generated for
+ @device: device/partition where bootloader should be installed to
+ @target: path of bootloader's configuration files"""
+
+ global UUID
+ UUID = get_uuid(target)
+ if options.skipsyslinuxconfig:
+ logging.info("Skipping generation of syslinux configuration as requested.")
+ else:
+ try:
+ handle_syslinux_config(grml_flavour, target)
+ except CriticalException, error:
+ logging.critical("Fatal: %s", error)
+ sys.exit(1)
+
+ if options.skipgrubconfig:
+ logging.info("Skipping generation of grub configuration as requested.")
+ else:
+ try:
+ handle_grub_config(grml_flavour, device, target)
+ except CriticalException, error:
+ logging.critical("Fatal: %s", error)
+ sys.exit(1)
+
+
+
+def install(image, device):
+ """Install a grml image to the specified device
+
+ @image: directory or is file
+ @device: partition or directory to install the device
+ """
+ iso_mountpoint = image
+ remove_image_mountpoint = False
+ if os.path.isdir(image):
+ logging.info("Using %s as install base", image)
+ else:
+ logging.info("Using ISO %s", image)
+ iso_mountpoint = tempfile.mkdtemp(prefix="grml2usb")
+ register_tmpfile(iso_mountpoint)
+ remove_image_mountpoint = True
+ try:
+ mount(image, iso_mountpoint, ["-o", "loop,ro", "-t", "iso9660"])
+ except CriticalException, error:
+ logging.critical("Fatal: %s", error)
+ sys.exit(1)
+
+ try:
+ install_grml(iso_mountpoint, device)
+ finally:
+ if remove_image_mountpoint:
+ try:
+ remove_mountpoint(iso_mountpoint)
+ except CriticalException, error:
+ logging.critical("Fatal: %s", error)
+ cleanup()
+
+
+
+def install_grml(mountpoint, device):
+ """Main logic for copying files of the currently running grml system.
+
+ @mountpoin: directory where currently running live system resides (usually /live/image)
+ @device: partition where the specified ISO should be installed to"""
+
+ device_mountpoint = device
+ if os.path.isdir(device):
+ logging.info("Specified device is not a directory, therefore not mounting.")
+ remove_device_mountpoint = False
+ else:
+ device_mountpoint = tempfile.mkdtemp(prefix="grml2usb")
+ register_tmpfile(device_mountpoint)
+ remove_device_mountpoint = True
+ try:
+ check_for_fat(device)
+ mount(device, device_mountpoint, ['-o', 'utf8,iocharset=iso8859-1'])
+ except CriticalException, error:
+ try:
+ mount(device, device_mountpoint, "")
+ except CriticalException, error:
+ logging.critical("Fatal: %s", error)
+ raise
+ try:
+ grml_flavours = identify_grml_flavour(mountpoint)
+ for flavour in set(grml_flavours):
+ if not flavour:
+ logging.warning("No valid flavour found, please check your iso")
+ logging.info("Identified grml flavour \"%s\".", flavour)
+ install_iso_files(flavour, mountpoint, device, device_mountpoint)
+ GRML_FLAVOURS.add(flavour)
+ finally:
+ if remove_device_mountpoint:
+ remove_mountpoint(device_mountpoint)
+
+def remove_mountpoint(mountpoint):
+ """remove a registred mountpoint
+ """
+
+ try:
+ unmount(mountpoint, "")
+ if os.path.isdir(mountpoint):
+ os.rmdir(mountpoint)
+ unregister_tmpfile(mountpoint)
+ except CriticalException, error:
+ logging.critical("Fatal: %s", error)
+ cleanup()
+
+def handle_mbr(device):
+ """Main handler for installing master boot record (MBR)
+
+ @device: device where the MBR should be installed to"""
+
+ if options.dryrun:
+ logging.info("Would install MBR")
+ return 0
+
+ if device[-1:].isdigit():
+ mbr_device = re.match(r'(.*?)\d*$', device).group(1)
+ partition_number = int(device[-1:]) - 1
+ else:
+ logging.warn("Could not detect partition number, not activating partition")
+ partition_number = None
+
+ # if we get e.g. /dev/loop1 as device we don't want to put the MBR
+ # into /dev/loop of course, therefore use /dev/loop1 as mbr_device
+ if mbr_device == "/dev/loop":
+ mbr_device = device
+ logging.info("Detected loop device - using %s as MBR device therefore", mbr_device)
+
+ mbrcode = GRML2USB_BASE + '/mbr/mbrldr'
+ if options.syslinuxmbr:
+ mbrcode = '/usr/lib/syslinux/mbr.bin'
+ elif options.mbrmenu:
+ mbrcode = GRML2USB_BASE + '/mbr/mbrldr'
+
+ try:
+ install_mbr(mbrcode, mbr_device, partition_number, True)
+ except IOError, error:
+ logging.critical("Execution failed: %s", error)
+ sys.exit(1)
+ except Exception, error:
+ logging.critical("Execution failed: %s", error)
+ sys.exit(1)
+
+
+def handle_vfat(device):
+ """Check for FAT specific settings and options
+
+ @device: device that should checked / formated"""
+
+ # make sure we have mkfs.vfat available
+ if options.fat16:
+ if not which("mkfs.vfat") and not options.copyonly and not options.dryrun:
+ logging.critical('Sorry, mkfs.vfat not available. Exiting.')
+ logging.critical('Please make sure to install dosfstools.')
+ sys.exit(1)
+
+ if options.force:
+ print "Forcing mkfs.fat16 on %s as requested via option --force." % device
+ else:
+ # make sure the user is aware of what he is doing
+ f = raw_input("Are you sure you want to format the specified partition with fat16? y/N ")
+ if f == "y" or f == "Y":
+ logging.info("Note: you can skip this question using the option --force")
+ else:
+ sys.exit(1)
+ try:
+ mkfs_fat16(device)
+ except CriticalException, error:
+ logging.critical("Execution failed: %s", error)
+ sys.exit(1)
+
+ # check for vfat filesystem
+ if device is not None and not os.path.isdir(device) and options.syslinux:
+ try:
+ check_for_fat(device)
+ except CriticalException, error:
+ logging.critical("Execution failed: %s", error)
+ sys.exit(1)
+
+ if not os.path.isdir(device) and not check_for_usbdevice(device) and not options.force:
+ print "Warning: the specified device %s does not look like a removable usb device." % device
+ f = raw_input("Do you really want to continue? y/N ")
+ if f == "y" or f == "Y":
+ pass
+ else:
+ sys.exit(1)
+
+
+def handle_compat_warning(device):
+ """Backwards compatible checks
+
+ @device: device that should be checked"""
+
+ # make sure we can replace old grml2usb script and warn user when using old way of life:
+ if device.startswith("/mnt/external") or device.startswith("/mnt/usb") and not options.force:
+ print "Warning: the semantics of grml2usb has changed."
+ print "Instead of using grml2usb /path/to/iso %s you might" % device
+ print "want to use grml2usb /path/to/iso /dev/... instead."
+ print "Please check out the grml2usb manpage for details."
+ f = raw_input("Do you really want to continue? y/N ")
+ if f == "y" or f == "Y":
+ pass
+ else:
+ sys.exit(1)
+
+
+def handle_logging():
+ """Log handling and configuration"""
+
+ if options.verbose and options.quiet:
+ parser.error("please use either verbose (--verbose) or quiet (--quiet) option")
+
+ if options.verbose:
+ FORMAT = "Debug: %(asctime)-15s %(message)s"
+ logging.basicConfig(level=logging.DEBUG, format=FORMAT)
+ elif options.quiet:
+ FORMAT = "Critical: %(message)s"
+ logging.basicConfig(level=logging.CRITICAL, format=FORMAT)
+ else:
+ FORMAT = "%(message)s"
+ logging.basicConfig(level=logging.INFO, format=FORMAT)
+
+
+def handle_bootloader(device):
+ """wrapper for installing bootloader
+
+ @device: device where bootloader should be installed to"""
+
+ # Install bootloader only if not using the --copy-only option
+ if options.copyonly:
+ logging.info("Not installing bootloader and its files as requested via option copyonly.")
+ elif os.path.isdir(device):
+ logging.info("Not installing bootloader as %s is a directory.", device)
+ else:
+ install_bootloader(device)
+
+
+def check_options(opts):
+ """Check compability of provided user opts
+
+ @opts option dict from OptionParser
+ """
+ if opts.grubmbr and not opts.grub:
+ logging.critical("Error: --grub-mbr requires --grub option.")
+ sys.exit(1)
+
+
+def check_programs():
+ """check if all needed programs are installed"""
+ if options.grub:
+ if not which("grub-install"):
+ logging.critical("Fatal: grub-install not available (please install the "
+ + "grub package or drop the --grub option)")
+ sys.exit(1)
+
+ if options.syslinux:
+ if not which("syslinux"):
+ logging.critical("Fatal: syslinux not available (please install the "
+ + "syslinux package or use the --grub option)")
+ sys.exit(1)
+
+ if not which("rsync"):
+ logging.critical("Fatal: rsync not available, can not continue - sorry.")
+ sys.exit(1)
+
+def main():
+ """Main function [make pylint happy :)]"""
+
+ if options.version:
+ print os.path.basename(sys.argv[0]) + " " + PROG_VERSION
+ sys.exit(0)
+
+ if len(args) < 2:
+ parser.error("invalid usage")
+
+ # log handling
+ handle_logging()
+
+ # make sure we have the appropriate permissions
+ check_uid_root()
+
+ check_options(options)
+
+ logging.info("Executing grml2usb version %s", PROG_VERSION)
+
+ if options.dryrun:
+ logging.info("Running in simulation mode as requested via option dry-run.")
+
+ check_programs()
+
+ # specified arguments
+ device = args[len(args) - 1]
+ isos = args[0:len(args) - 1]
+
+ if not os.path.isdir(device):
+ if device[-1:].isdigit():
+ if int(device[-1:]) > 4 or device[-2:].isdigit():
+ logging.critical("Fatal: installation on partition number >4 not supported. (BIOS won't support it.)")
+ sys.exit(1)
+
+ # provide upgrade path
+ handle_compat_warning(device)
+
+ # check for vfat partition
+ handle_vfat(device)
+
+ # main operation (like installing files)
+ for iso in isos:
+ install(iso, device)
+
+ # install mbr
+ is_superfloppy = not device[-1:].isdigit()
+ if is_superfloppy:
+ logging.info("Detected superfloppy format - not installing MBR")
+
+ if not options.skipmbr and not os.path.isdir(device) and not is_superfloppy:
+ handle_mbr(device)
+
+ handle_bootloader(device)
+
+ logging.info("Note: grml flavour %s was installed as the default booting system.", GRML_DEFAULT)
+
+ for flavour in GRML_FLAVOURS:
+ logging.info("Note: you can boot flavour %s using '%s' on the commandline.", flavour, flavour)
+
+ # finally be politely :)
+ logging.info("Finished execution of grml2usb (%s). Have fun with your grml system.", PROG_VERSION)
+
+
+if __name__ == "__main__":
+ try:
+ main()
+ except KeyboardInterrupt:
+ logging.info("Received KeyboardInterrupt")
+ cleanup()