#!/bin/sh

# Simple script to build FreeBSD -current for the Cavium Octeon processor.
# This script assumes that:
#	o sources are in ~/svn/head
#	o object directory is ~/obj
#	o root installed into ~/roots/octeon
#	o a compressed image for a 1GB CF card will be left in
#	  ~/roots/octeon.image.xz

# To use, plug in your CF card to a FreeBSD system, it will show up as daX.
# Next, put the image onto the CF:
#	xzcat ~/roots/allo.image.xz | dd of=/dev/daX bs=1m
# remove the CF from the FreeBSD system, and place it into the Cavium eval
# board.
# Load in the image with the following command:
#	fatload ide 0 $(loadaddr) kernel
# once it has loaded successfully, you can boot the kernel with the following
# command:
#	bootoctlinux $(loadaddr)
#
# The system will come up multi-user.  There's no root password.  It will try
# to get its IP address from octe0 via dhcp.  No services are started.  The
# typical console speed is 115200.
#
# If you don't want it to build everything from scratch, set do_build to false
#
# This script must be run as root.

image_name=octeon
export TARGET=mips
export TARGET_ARCH=mips64eb
export DESTDIR=${HOME}/roots/${image_name}
export SRCDIR=${HOME}/svn/head
export MAKEOBJDIRPREFIX=${HOME}/obj
# 930MiB is just shy of 1GB in bytes
IMG_SIZE=$((930 * 1024 * 1024))
DOS_SECTORS=$(( (930-760) * 1024 * 2))
do_build=false
CLEAN=-DNO_CLEAN
KERNCONF=OCTEON1

JOBS=20

mkdir -p ${DESTDIR}
cd ${SRCDIR}
if ${do_build}; then
    make buildworld ${CLEAN} -j ${JOBS}
    make buikdkernel ${CLEAN} KERNCONF=${KERNCONF} -j ${JOBS}
fi
make installworld DESTDIR=${DESTDIR}
make distribution DESTDIR=${DESTDIR}
make installkernel KERNCONF=${KERNCONF} DESTDIR=${DESTDIR}
cat <<EOF > ${DESTDIR}/etc/fstab
# Device		Mountpoint	FStype	Options		Dump	Pass#
/dev/cf0s2a		/		ufs	rw		1	1
/dev/cd0s1		/dos		msdosfs	rw,noauto	0	0
EOF
echo 'hostname=octeon-image' > ${DESTDIR}/etc/rc.conf
echo 'ifconfig_octe0=DHCP' >> ${DESTDIR}/etc/rc.conf
mkdir ${DESTDIR}/dos
cat <<EOF >> ${DESTDIR}/etc/motd

Octeon Image built with imp's mkoctimage script
EOF
makefs -f 20% -B big -s 760m ${DESTDIR}.ufs ${DESTDIR}
cp /dev/null ${DESTDIR}.image
dd if=/dev/zero of=${DESTDIR}.image oseek=${IMG_SIZE} bs=1 count=0
md=$(mdconfig -f ${DESTDIR}.image)
gpart create -s mbr ${md}
gpart add -t !6 -s ${DOS_SECTORS} ${md}
gpart add -t freebsd ${md}
gpart create -s BSD ${md}s2
gpart add -b 16 -t freebsd-ufs ${md}s2
dd if=${DESTDIR}.ufs of=/dev/${md}s2a bs=1m
newfs_msdos -F 16 /dev/${md}s1
mount -t msdosfs /dev/${md}s1 /mnt
cp ${DESTDIR}/boot/kernel/kernel /mnt
umount /mnt
mdconfig -d -u ${md}
xz -9f ${DESTDIR}.image
