#!/bin/sh
set -e

. /usr/share/debconf/confmodule

log() {
	logger -t sibyl-installer "$@"
}

error() {
	log "error: $@"
}

info() {
	log "info: $@"
}

findfs () {
	mount | grep "on /target${1%/} " | cut -d' ' -f1
}

db_progress START 0 3 sibyl-installer/progress

# detect the /target partition
rootfs_devfs=$(findfs /)

rootfs=$(mapdevfs $rootfs_devfs)
bootdev=`echo $rootfs | sed 's/[0-9]\+$//'`

db_progress INFO sibyl-installer/apt-install

if ! apt-install sibyl ; then
	info "Calling 'apt-install sibyl' failed"
	db_input critical sibyl-installer/apt-install-failed || [ $? -eq 30 ]
	if ! db_go; then
		exit 10 # back up to menu
	fi
	db_get sibyl-installer/apt-install-failed
	if [ true != "$RET" ] ; then
		exit 1
	fi
else
	case "`archdetect`" in
		mips/*)
			FLAG="-EB"
		;;
		mipsel/*)
			FLAG="-EL"
		;;
		*)
			error "Unknown architecture `archdetect`"
		;;
	esac
	info "Installing sibyl.bin to $bootdev with flag $FLAG"
	chroot /target /usr/sbin/installboot $FLAG /usr/lib/sibyl/sibyl.bin $bootdev
fi

db_progress STEP 2
db_progress INFO sibyl-installer/conf

# The kernel path should not start with a / because SiByl cannot handle
# that.
kernel=`find /target/boot -name 'vmlinu*sb1*' | tail -n 1`
kernel=${kernel#/target/boot/}
info "Using kernel '$kernel'"

# /boot has to be on a separate partition because SiByl can only
# read from the top-level directory.
cat > /target/boot/sibyl.conf <<EOF
timeout=5;
default=debian;
prompt;

config debian {
    kernel=ext2:ide0.0:*:$kernel;
    root_dev=$rootfs;
    extra_args=console=duart0;
}

EOF

db_progress STEP 1
db_progress STOP

