#!/bin/sh
# Wrapper around nanobsd.sh with autodetection of already processed steps
# to provide some failsafe net

BASEDIR=`dirname $0`
. ${BASEDIR}/package-build.inc.sh

NANOBSD="$NANO_SRC/tools/tools/nanobsd/nanobsd.sh"

FORCE_KERNEL=0
FORCE_WORLD=0
#XXX: Proper object handling
if [ "$1" = "-bk" ]; then
  p_warn Forcefully building kernel
  FORCE_KERNEL=1
elif [ "$1" = "-bw" ]; then
  p_warn Forcefully building world
  FORCE_WORLD=1
elif [ "$1" = "-f" ]; then
  p_warn Forcefully building world and kernel
  FORCE_KERNEL=1
  FORCE_WORLD=1
fi
shift
NANOBSD_EXTRA=$*

if [ ! -r "${NANOBSD}" ]; then
  p_err ${NANOBSD} does not exists
  exit 1
fi

if [ ! -x "${NANOBSD}" ]; then
  NANOBSD="sh ${NANOBSD}"
fi

# Find object directory 
OBJDIR="/usr/obj/nanobsd.${NANO_NAME}"

if [ -d "${OBJDIR}" ]; then
  NANOBSD_FLAGS=""
  
  # Detect succesfull buildworld
  tail -10 ${OBJDIR}/_.bw | grep 'World build completed'
  if [ $? -eq 0 -a ${FORCE_WORLD} -eq 0 ]; then
     p_info NO building of world, use $0 -f to force
     NANOBSD_FLAGS="${NANOBSD_FLAGS} -w"
  fi  

  # Detect succesfull buildkernel
  tail -10 ${OBJDIR}/_.bk | grep 'Kernel build for .* completed'
  if [ $? -eq 0 -a ${FORCE_KERNEL} -eq 0 ]; then
     p_info NO building of kernel, use $0 -f to force
     NANOBSD_FLAGS="${NANOBSD_FLAGS} -k"
  fi  

else
  p_warn Nothing yet, starting fresh
  NANOBSD_FLAGS=""
fi

# Provide verbose output by default
COMMAND="${NANOBSD} ${NANOBSD_FLAGS} -c ${NANO_CFG_FILE} -v ${NANOBSD_EXTRA}"
f_time ${COMMAND}
RETVAL=$?

# Verify on build failures
tail -10 ${OBJDIR}/_.bw | grep 'World build completed'
if [ $? -eq 1 ]; then
  p_err Building world FAILED, check ${OBJDIR}/_.bw
fi
tail -10 ${OBJDIR}/_.bk | grep 'Kernel build for .* completed'
if [ $? -eq 1 ]; then
  p_err Building kernel FAILED, check ${OBJDIR}/_.bk
fi  
if [ $RETVAL -ne 0 ]; then
  p_err "Errors in building NanoBSD Image ($RETVAL)"
fi
p_info End time: `date`
exit ${RETVAL}
