#!/bin/sh
set -e

# Program to search for disks with a PReP boot partition, and then
# prompt the user for which one to install the kernel on.
#
# Copyright (C) 2005 Sven Luther <luther@debian.org>

. /usr/share/debconf/confmodule

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

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

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

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

writefile () {
    cat >>"$1" || die prep-installer/conferr "Error writing $2"
}

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

db_capb backup

db_progress START 0 3 prep-installer/progress

die() {
    template="$1"
    shift

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

# Find the boot partition

db_progress STEP 1
db_progress INFO prep-installer/part

ARCH="$(archdetect)"
info "architecture: $ARCH"

PARTITIONS=
DEFAULT=
bootdev_priority=critical

if ([ "$ARCH" = powerpc/prep ] || [ "$ARCH" = powerpc/chrp_rs6k ] || [ "$ARCH" = powerpc/chrp_ibm ]) && \
	db_get partman-prep/boot_partitions && [ "$RET" ]; then
    for part in $RET; do
	if [ -z "$PARTITIONS" ]; then
	    DEFAULT="$part"
	    PARTITIONS="$part"
	else
	    PARTITIONS="$PARTITIONS,$part"
	fi
    done
    info "partman-supplied bootstrap partitions: $PARTITIONS"
    info "partman-supplied default bootstrap partition: $DEFAULT"
    if [ "$PARTITIONS" ] && [ "$DEFAULT" = "$PARTITIONS" ]; then
	# We have explicit information from partman-prep that only one
	# bootstrap partition is available, so it's safe to bypass this
	# question.
	bootdev_priority=medium
    fi
fi

if [ -z "$PARTITIONS" ]; then
    # error: no viable boot partitions found; fall over
    die prep-installer/nopart 'No prep boot partitions found'
fi

KERNEL=`ls /target/boot/vmlinuz-2.*`

# Well, we make it simple, since we can ensure that partman-prep will allow
# for only one prep partition for now, so we will simply install in the first
# one provided, without any questions or whatnot.

db_progress STEP 1
db_progress INFO prep-installer/dd

dd if=$KERNEL of=$DEFAULT

db_progress STEP 1
db_progress STOP

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