#!/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 "/target$1" | sed '1d;s/[[:space:]].*//'
}

write_conf () {

    cat > /target/vmelilo.conf << EOF || die vmelilo-installer/conferr "Error writing /target/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
}

write_bootblock () {

    case $SUBARCH in
	bvme6000)
            vmearch = bvme
            ;;
	mvme16x|mvme147)
            vmearch = mvme
            ;;
    esac
    
    LD_LIBRARY_PATH=\"/target/lib:/target/usr/lib\" /target/sbin/vmelilo -f -w /target || die vmelilo-installer/booterr "Error writing vmelilo"
}


# 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 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/[0-9]//g'"
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

db_input medium vmelilo-installer/success || [ $? -eq 30 ]
db_go

