Skip to content

Instantly share code, notes, and snippets.

@chrisandreae
Created January 21, 2021 10:55
Show Gist options
  • Save chrisandreae/e9a561b9b32a6b44dd0b5afe11787206 to your computer and use it in GitHub Desktop.
Save chrisandreae/e9a561b9b32a6b44dd0b5afe11787206 to your computer and use it in GitHub Desktop.
Parse nixos extlinux boot and boot a vm with vftool
require 'optparse'
require 'tempfile'
require 'json'
def parse_extlinux(file)
globals = {}
labels = {}
target = globals
file.lines.each do |line|
line = line.strip
next if line.empty?
next if line =~ /^#/
key, value = line.split(' ', 2)
if key == 'LABEL'
target = labels[value] = {}
else
target[key] = value
end
end
[globals, labels]
end
def default_config(globals, labels)
default = globals.fetch('DEFAULT') { labels.each_key.first }
labels[default].merge(globals)
end
options = {}
OptionParser.new do |opts|
opts.on('-b', '--boot BOOT', 'Boot disk image (fat32)')
opts.on('-r', '--root ROOT', 'Root disk image')
# vftool arguments
opts.on('-c', '--cdrom path', 'cdrom image path')
opts.on('-p', '--processors count', 'number of processors')
opts.on('-m', '--memory size', 'memory size in mb')
opts.on('-t', '--tty type', 'tty type')
end.permute!(into: options)
config_file = `mcopy -i "#{options[:boot]}" "::/extlinux/extlinux.conf" -`
raise 'no config' unless $?.success?
config = default_config(*parse_extlinux(config_file))
kernel = Tempfile.new
system('mcopy', '-n', '-i', options[:boot], "::/extlinux/#{config.fetch('LINUX')}", kernel.path) or raise('no kernel')
initrd = Tempfile.new
system('mcopy', '-n', '-i', options[:boot], "::/extlinux/#{config.fetch('INITRD')}", initrd.path) or raise('no initrd')
vftool_args = [
'-k', kernel.path,
'-i', initrd.path,
'-a', config.fetch('APPEND'),
'-d', options[:root],
'-d', options[:boot]
]
opt_mapping = { cdrom: '-c', processors: '-p', memory: '-m', tty: '-t' }
opt_mapping.each do |option, arg|
if (opt = options[option])
vftool_args << arg << opt
end
end
STDERR.puts "vftool #{vftool_args.join(' ')}"
exec('vftool', *vftool_args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment