#!/usr/bin/perl -w

# This script generates a disk image from a FreeBSD bootonly iso image.
# The generated script is well suited for being loaded by memdisk from
# the Syslinux package.
#
# A sample menu.lst entry looks like this:
#
# title sysinstall
#   kernel /boot/memdisk
#   initrd /boot/disk.img

use strict;
use POSIX;

my $cwd = getcwd;

if (@ARGV != 2) {
	print STDERR "Usage: iso2diskimage.pl <isofile> <diskimage>\n";
	exit 1;
}

my ($iso, $img) = @ARGV;

if ($iso !~ /^\//) {
	$iso = "$cwd/$iso";
}

my $size = (stat($iso))[7];

system "truncate -s ".($size + 20000000)." $img";
my $md = `sudo mdconfig -a -t vnode -f $img`;
chomp $md;

system "sudo fdisk -IB /dev/$md";
system "sudo bsdlabel -Bw /dev/${md}s1";
system "sudo newfs -U /dev/${md}s1a";
system "sudo mount /dev/${md}s1a /mnt";
system "cd /mnt; sudo tar -xf $iso";
system "sudo umount /mnt";
system "sudo mdconfig -d -u $md";
