#!/bin/sh

# $Id$

# Soekris pxe/cf image build

P=`pwd`
bootmk=/usr/src/sys/boot/i386/libi386/Makefile
export __MAKE_CONF=$P/make.conf

if [ ! -r make.conf ]; then
   exit
fi

case "$1" in
   pxe)
      kern=PXE
      D=/usr/tftpboot
      export MAKEOBJDIRPREFIX=/usr/objpxe
   ;;
   cf)
      kern=AP
      D=/usr/ap
      export MAKEOBJDIRPREFIX=/usr/objap
   ;;
   *)
      echo "Usage: $0 {pxe|cf}"
      exit 1
   ;;
esac

remove () {
   if [ -d "$1" ]; then
      inode=`ls -di $1 | sed 's/ .*//'`
      mv $1 $1.$inode
      rm -rf $1.$inode &
   else
     echo "remove($1) is not a dir!" && exit
   fi
}

chflags -R noschg $D
remove $D

set -v
mkdir -p $D/usr/libexec
ln -s $D/usr/libexec/ld-elf.so.1 $D/libexec/ld-elf.so.1
# Build world
remove ${MAKEOBJDIRPREFIX}/usr
mv ${bootmk} ${bootmk}~
grep -v DTERM_EMU < ${bootmk}~ > ${bootmk}
cd /usr/src
make buildworld
status=$?
mv ${bootmk}~ ${bootmk}
[ $status -ne 0 ] && exit

# Install world to $D

mkdir -p $D
make installworld DESTDIR=$D NOMAN=yes || exit
cd etc
make distribution DESTDIR=$D
(cd /etc;cp -p group pwd.db passwd spwd.db master.passwd $D/etc)
mkdir -p $D/conf/base/etc
cp -Rp $D/etc $D/conf/base
#rm -rf $D/etc # Need by init
mkdir -p $D/conf/default/etc
cp -Rp $P/etc/* $D/conf/default/etc
if [ $kern = "PXE" ]; then
   mv $D/conf/default/etc/fstab.nfs $D/conf/default/etc/fstab
   mv $D/conf/default/etc/rc.conf.nfs $D/conf/default/etc/rc.conf
else
   touch $D/etc/diskless
fi
echo "PermitRootLogin yes" >> $D/conf/base/etc/ssh/sshd_config
cp -p $D/conf/default/etc/fstab $D/etc/fstab
cp $P/boot/* $D/boot

# Build a custom kernel

rm -rf /usr/src/sys/i386/compile/$kern
cd /usr/src/sys/i386/conf
mv AP AP~
cp GENERIC AP
patch < $P/AP.diff
if [ $kern = "PXE" ]; then
mv AP PXE
mv AP~ AP
cat >> PXE <<EOF

options     BOOTP          # Use BOOTP to obtain IP address/hostname
options     BOOTP_NFSROOT  # NFS mount root filesystem using BOOTP info
options     BOOTP_COMPAT   # Workaround for broken bootp daemons.
EOF
fi
config $kern
cd /usr/src/sys/i386/compile/$kern
cp /usr/src/sys/i386/conf/GENERIC.hints $D/boot/device.hints
make clean depend all
make DESTDIR=$D install
gzip -9 $D/boot/kernel/kernel

cp -Rp $P/usr $D

# Add a few packages

du -sh $D
pkg_add -p $D/usr/local -R \
ftp://ftp.FreeBSD.org/pub/FreeBSD/ports/i386/packages-current/All/dnsmasq-2.2.tbz
pkg_add -p $D/usr/local -R \
ftp://ftp.FreeBSD.org/pub/FreeBSD/ports/i386/packages-current/All/isc-dhcp3-server-3.0.1.r12.tbz


# Prune installation

du -sh $D
rm -rf $D/usr/share/dict/*
rm -rf $D/usr/share/examples/*
rm -rf $D/usr/lib/*.[oa]
rm -rf $D/usr/include/*
du -sh $D