#! /usr/bin/perl

# Script to create a LILO boot floppy using a normal /etc/lilo.conf.
#
# Usage:
#   mk_boot_floppy [root_dir]
#
#   root_dir: the directory the root partition is mounted to (defaults to "/")
#
# Example:
#
# mk_boot_floppy /
#
# on errors:
#   exit code > 0
#
# Version 2.0
#
# Author: Steffen Winterfeldt <wfeldt@suse.de>
# (c) 2001 SuSE GmbH

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# general configurable parameters

$rootdir = $ENV{'root_dir'} ? $ENV{'root_dir'} : "/";
$rootdir = shift if @ARGV != 0;

# boot floppy image we create
$bootfloppy = "$rootdir/boot/floppy";

# relative to $rootdir
$boot = "/boot";

$floppy = $ENV{'floppy'} ? $ENV{'floppy'} : "/dev/fd0";

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# should be nothing to change below...

$tmp_msg = "/tmp/msg$$";
$tmp_boot = "/tmp/boot$$";
$tmp_mnt = "/tmp/mnt$$";

END {
  system "umount $tmp_mnt" if $is_mounted;
  system "rm -f $tmp_msg $tmp_boot";
  system "rmdir $tmp_mnt" if -d $tmp_mnt;

  exit 21;
}

system "dd if=/dev/zero of=$tmp_boot bs=1k count=1440";
system "mke2fs -q -F -b 1024 -m 0 $tmp_boot";
system "tune2fs -i 0 $tmp_boot";

system "mkdir $tmp_mnt";
system "mount -t ext2 -oloop=/dev/loop7 $tmp_boot $tmp_mnt" and
  die "failed to mount boot disk image\n";

$is_mounted = 1;

system "rmdir $tmp_mnt/lost+found";

@cfg = `cat $rootdir/etc/lilo.conf`;

for (@cfg) { s#^\s*boot\s*=\s*/dev/.*$#boot\t= $floppy# }

for (@cfg) {
  if(s#^\s*boot\s*=\s*/dev/.*$#boot\t= $floppy#) {
    push @new_cfg, $_;
    push @l_cfg, "boot\t= /dev/loop7\n";

    next;
  }

  $image_cnt++ if /^\s*image\s*=/;
  last if $image_cnt > 1;

  if(s#^(\s*(message|image|initrd)\s*=\s*)($boot(/\S+))(.*)#$1$4$5#) {
    push @files, "$boot$4";
    push @l_cfg, "$1$tmp_mnt$4$5\n";
  } else {
    push @l_cfg, $_;
  }

  push @new_cfg, $_;
}

open F, ">$tmp_mnt/lilo.conf"; print F @new_cfg; close F;
open F, ">$tmp_msg"; print F @l_cfg; close F;

system "cp $rootdir$boot/boot.b $tmp_mnt" and
  die "not enough space on boot disk\n";

for (@files) {
  system "cp $rootdir/$_ $tmp_mnt" and die "not enough space on boot disk\n"
}

system "lilo -v -v -v -C $tmp_msg -i $tmp_mnt/boot.b -m $tmp_mnt/map >$rootdir/$boot/lilofloppy.log" and
  die "lilo failed\n";

system "umount $tmp_mnt";
undef $is_mounted;

system "cp $tmp_boot $bootfloppy" and die "failed to copy boot disk\n";

system "losetup -d /dev/loop7 2>/dev/null";

exit 0;
