#!/bin/sh
set -e

. /usr/share/debconf/confmodule

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

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

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

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

die() {
    template="$1"
    shift

    error "$@"
    db_input critical "$template" || [ $? -eq 30 ]
    db_go
    db_progress STOP
    exit 1
}

findfs () {
    df -h "/target$1" | sed '1d;s/[[:space:]].*//'
}

write_conf () {

    case $BOOTDEV in
        /dev/scsi*)
	  BOOTDEV=$(mapdevfs $BOOTDEV)
	  ROOTDEV=$(mapdevfs $ROOTDEV)
	;;
    esac
    cat > /target/etc/vmelilo.conf << EOF || die vmelilo-installer/conferr "Error writing /target/etc/vmelilo.conf"

## vmelilo.conf generated by debian-installer
##
## "man vmelilo.conf" for details. 
## see also /usr/share/doc/vmelilo/examples for example configurations.

default   = Linux
boot      = $BOOTDEV
delay     = 2

[boot]
label     = Linux
image     = /vmlinuz
root      = $ROOTDEV
read-only
EOF
    sed -i -e 's/do_bootloader[ ]*=[ ]*no/do_bootloader = yes/' /target/etc/kernel-img.conf
}

write_bootblock () {

    case $SUBARCH in
	bvme6000)
            vmearch=bvme
            ;;
	mvme16x|mvme147)
            vmearch=mvme
            ;;
    esac
    
    case $(uname -r) in
      2.2*)
    	LD_LIBRARY_PATH=\"/target/lib:/target/usr/lib\" /target/sbin/vmelilo -f -w /target || die vmelilo-installer/booterr "Error writing vmelilo"
	;;
      2.4*)
        mount -t proc proc /target/proc
        chroot /target /sbin/vmelilo -f || die vmelilo-installer/booterr "Error writing vmelilo"
	umount /target/proc
	;;
    esac
}


# Install vmelilo in /target 

db_progress START 0 4 vmelilo-installer/progress

db_get debian-installer/kernel/subarchitecture
SUBARCH="$RET"
info "subarchitecture: $SUBARCH"

db_progress INFO vmelilo-installer/apt-install

if ! apt-install vmelilo; then
    info "Calling 'apt-install vmelilo' failed"
    db_input critical vmelilo-installer/apt-install-failed || [ $? -eq 30 ]
    if ! db_go; then
	db_progress STOP
	exit 10 # back up to menu
    fi
    db_get vmelilo-installer/apt-install-failed
    if [ "$RET" != true ]; then
	db_progress STOP
	exit 1
    fi
fi

db_progress STEP 1
db_progress INFO vmelilo-installer/root

ROOTDEV="$(findfs /)"
[ "$ROOTDEV" ] || die vmelilo-installer/noroot 'No root partition found'

BOOTDEV="`echo $ROOTDEV | sed -e 's/sd\([a-z]\)[0-9]*/sd\1/g' -e 's/part[0-9]*/disc/'`"
info "root: $ROOTDEV  boot: $BOOTDEV"

db_progress STEP 1
db_progress INFO vmelilo-installer/writeconf

write_conf 

db_progress STEP 1
db_progress INFO vmelilo-installer/writeboot

write_bootblock 

db_progress STEP 1
db_progress STOP

