#!/bin/sh

set -x -e

DISKIMG="FreeSBIE.iso"

DEF_DEV=/dev/da0

if [ \! -f "${DISKIMG}" ]; then
    echo "Could not find image ${DISKIMG}, aborting"
    exit 1;
fi

echo -n "Device where you want to install FreeSBIE [${DEF_DEV}]: "
read DEVICE

if [ "x${DEVICE}" = "x" ]; then
    DEVICE=$DEF_DEV
fi

if [ \! -c "${DEVICE}" ]; then
    echo "Unable to find ${DEVICE}, please check the pathname"
    exit 1;
fi


DISKMD=/dev/`mdconfig -a -t vnode -f ${DISKIMG}`
TEMP2DIR=$PWD/tmp2dir.$$

mkdir $TEMP2DIR
mount_cd9660 ${DISKMD} $TEMP2DIR


dd if=/dev/zero of=${DEVICE} bs=512 count=32
fdisk -BI ${DEVICE}
dd if=/dev/zero of=${DEVICE}s1 bs=512 count=32
bsdlabel -w -B ${DEVICE}s1
bsdlabel ${DEVICE}s1 >> tmp.$$
ed tmp.$$ <<EOF
/a:
s/unused/4.2BSD
wq
EOF
bsdlabel -R ${DEVICE}s1 tmp.$$
rm tmp.$$
newfs ${DEVICE}s1a

TEMPDIR=$PWD/tmpdir.$$
mkdir $TEMPDIR
mount ${DEVICE}s1a $TEMPDIR

cd $TEMP2DIR
find . -depth -print | cpio -pvudm $TEMPDIR


if [ -f "dist/FreeSBIE.root.dist.bz2" ]; then
    bzcat dist/FreeSBIE.root.dist.bz2 | mtree -PUr -p $TEMPDIR
fi

cd ..

umount $TEMPDIR
rmdir $TEMPDIR


umount $TEMP2DIR
rmdir $TEMP2DIR
mdconfig -d -u `echo ${DISKMD} | sed s/\\\/dev\\\/md//g`

