#!/usr/bin/perl
#
# /usr/sbin/siloconfig	configure silo automatically
# this program is a modified version of liloconfig
# which is copyright by
# Author:	Bruce Perens <bruce@Pixar.com>
# Maintainer:	Bernd Eckenfels <ecki@debian.org>

# siloconfig (C) 1998 Davide Barbieri <paci@debian.org>
#            (C) 2001 Ben Collins <bcollins@debian.org>
# this software is GPLed

$|=1;

if ( ! (-f "/etc/fstab") ) {
	exit(0);
}

if ($ENV{'DEBIAN_FRONTEND'} eq "noninteractive") {
	print "\nNon-interactive, skipping silo configuration.\n";
	exit(0);
}

print "SILO, the Sparc Improved LOader, sets up your system to boot Linux\n";
print "directly from your hard disk, without the need for a boot floppy or a net\n";
print "boot.\n";

@boilerplate = (
	"timeout=20\n\n",
	"image=/vmlinuz\n",
	"\tlabel=Linux\n",
	"\tread-only\n\n",
	"image=/vmlinuz.old\n",
	"\tlabel=LinuxOLD\n",
	"\tread-only\n"
);

sub asky {
	print @_,"? [Yes] ";
	$answer=<STDIN>;
	return ( !($answer =~ /^[nN].*/) );
}

sub askn {
	print @_,"? [No] ";
	$answer=<STDIN>;
	return ( $answer =~ /^[yY].*/ );
}

$realconf = "/boot/silo.conf";


if (! -f $realconf) {
	# This is an upgrade case
	if (-f "/etc/silo.conf") {
		system("cp /etc/silo.conf /boot/silo.conf");
		unlink("/etc/silo.conf");
	}
	# This is boilerplate for new installs, or conversion for upgrades
	symlink("/boot/silo.conf", "/etc/silo.conf");
	symlink(".", "/boot/etc");
	symlink(".", "/boot/boot");
}

if (-T $realconf) {
	# Trust and use the existing silo.conf.
	print "\n";
	print "You already have a SILO configuration in the file $realconf\n";
	if ( &asky("Install a boot block using your current SILO configuration") ) {
		print "Running silo\n";
		system("/sbin/silo -f");
		exit(0);
	} else {
		print "\n";
		if ( &askn("Wipe out your old SILO configuration and make a new one") ) {
			print "Saving configuration in $realconf.OLD\n";
			rename("$realconf", "$realconf.OLD");
		} else {
			print "No changes made.\n";
			exit(0);
		}
	}
}

# Create a silo.conf if one doesn't exist.
open(FSTAB, "</etc/fstab");
while ( $line=<FSTAB> ) {
	if ( $line =~ m/^\#/ ) {
		next;
	}
	($device,$filesystem)=split(/[ \t]+/, $line);
	if ( $filesystem =~ m:^/$: ) {
		last;
	}
}
if ( ! $filesystem =~ m:^/$: ) {
	exit(0);
}

$disk = $device;
$disk =~ s/[0-9]+$//;
$partition = $device;
$partition =~ s/$disk//;

if ( &asky("Install a partition boot record to boot Linux from ", $device)) {
        print "Creating small silo.conf and running silo.\n";
	umask(022);
	open(CONF, "> $realconf");
	chown(0, 0, "$realconf");
	print CONF "partition=".$partition, "\n", "root=".$device, "\n", @boilerplate;
	close(CONF);
	system("/sbin/silo -f");
}

exit(0);
