#!/usr/bin/perl

@ARGV >= 2 or die "usage: $0 <image> cdrom|hd|network|network_ks|pcmcia\n";

($img, $type) = @ARGV;

$instdir = "install";
$ks = "kickstart=floppy" if $type =~ s/_ks//;
$mnt = "/mnt/disk";
if ($>) {
    $sudo = "sudo";
    $ENV{PATH} = "/sbin:/usr/sbin:$ENV{PATH}";
}


$install = $ {{
    pcmcia => "install",
    network => "install",
    cdrom => "local-install",
    hd => "local-install"
}}{$type} or die;

$0 =~ /initrd/ ?
    initrd($mnt, $img) :
    boot_img($mnt, $img);

sub __ { print @_, "\n"; system(@_); }
sub _ { __ @_; $? and die; }


sub initrd {
    my ($mnt, $img) = @_;
    my $tmp = "$ENV{HOME}/tmp/initrd";
    my $inst1 = -d "$instdir/install1_$type" ? "install1_$type" : "install1";

    _ "install -s $instdir/installinit/init $instdir/$inst1/sbin/init";
    _ "install -s $instdir/$install $instdir/$inst1/sbin/install";

    __ "$sudo umount $tmp $mnt 2>/dev/null";
    _ "dd if=/dev/zero of=$tmp bs=1k count=2000";
    _ "echo y | mke2fs $tmp";
    _ "$sudo mount -t ext2 $tmp $mnt -o loop";
    _ "$sudo cp -a $instdir/$inst1/* $mnt";
    _ "$sudo cp -f install_${type}_modules/* $mnt/modules/" if -d "install_${type}_modules";
    _ "$sudo cp -f modules/${type}_modules.cgz $mnt/modules/modules.cgz";
    _ "$sudo cp -f modules/modules.dep $mnt/modules/";
    _ "$sudo umount $mnt";
    _ "gzip -9 -c $tmp > $img";
    _ "rm -f $tmp";
}

sub boot_img {
    my ($mnt, $img) = @_;

    __ "$sudo umount $mnt 2>/dev/null";
    _ "bunzip2 -c $instdir/installinit/emptyboot.img.bz2 > $img";
    _ "$sudo mount -t msdos -o umask=0 $img $mnt -o loop";
    _ "cat vmlinuz > $mnt/vmlinuz";
    initrd("${mnt}2", "$mnt/$type.rdz");
    
    output("$mnt/syslinux.cfg", "
default linux
prompt 0
label linux
  kernel vmlinuz
  append $ks ramdisk=32000 initrd=$type.rdz mdkinst $type
");
    _ "cp -f $instdir/installinit/ks.cfg $mnt 2>/dev/null" if $ks;
    _ "sync";
}



sub output {
    my $f = shift;
    local *F;
    open F, "> $f" or die "error writing to $f";
    print F join '', @_;
}