#!/bin/sh
set -e

. /usr/share/debconf/confmodule
db_capb backup

findfs () {
        check=$(mount | grep "on /target${1%/} " | cut -d' ' -f1)
        if [ -n "$check" ]; then
		mapdevfs $check
	fi
}

# detect the partitions /target and /target/boot
rootfs=$(findfs /)
bootfs=$(findfs /boot)
[ -n "$bootfs" ] || bootfs="$rootfs"
bootpart=${bootfs#${bootfs%?}}

if [ "$rootfs" = "$bootfs" ]; then
	boot="/boot"
else
	boot=""
fi

# force -t on raid
if echo "$bootfs" | grep -q "/dev/md"; then
	raidinstall=y
else
	raidinstall=n
fi

if [ -e "/target/boot/initrd.img" ]; then
	initrd="initrd=${boot}/initrd.img"
	initrdold="${initrd}.old"
else
	initrd=""
	initrdold=""
fi

# Install silo
if ! apt-install silo; then
        db_input critical silo-installer/apt-install-failed || [ $? -eq 30 ]
        db_go
        db_get silo-installer/apt-install-failed
        if [ "$RET" = false ]; then
                db_stop
                exit 1
        fi
fi
         

# Write out silo.conf
cat > /target/boot/silo.conf << EOF
root=${rootfs}
partition=${bootpart}
default=Linux
read-only
timeout=100
append="quiet splash"

image=${boot}/vmlinuz
	label=Linux
	${initrd}

image=${boot}/vmlinuz.old
	label=LinuxOLD
	${initrdold}
EOF

chmod 644 /target/boot/silo.conf

# Compat links
ln -sf ../boot/silo.conf /target/etc/silo.conf
ln -sf . /target/boot/boot
ln -sf . /target/boot/etc

if chroot /target /sbin/silo -f; then
	if [ "$raidinstall" = "y" ]; then
		chroot /target /sbin/silo -f -t >/dev/null 2>&1
	fi
	db_input medium silo-installer/success || [ $? -eq 30 ]
	db_go || true
	exit 0
else
	ERRCODE=$?
	db_subst silo-installer/failed ERRCODE "$ERRCODE"
	db_input critical silo-installer/failed || [ $? -eq 30 ]
	db_go || exit 10 # back up
	exit 1
fi

