#!/bin/sh
# Install all required packages
#
# XXX: Welcome to port hell, if /usr/ports has been updated, you actually want
# to delete all installed packages and start over again, hence why people used
# to run this stuff in jails, etc.
#
# Rick van der Zwet <rick@wirelessleiden.nl>
#

. `dirname $0`/package-build.inc.sh

DEBUG=${DEBUG:-'0'}

# Find listing of packages to build
PKG_TO_BUILD=${PKG_TO_BUILD:-${PACKAGE_LIST}}

# make options, for package building
LOGDIR=`mktemp -d /tmp/$(basename $0 .sh)-$(date '+%Y%m%d-%H:%M:%S')X`

p_info Log directory ${LOGDIR}
p_info Make arguments are:
p_info `p_list ${PKG_MAKE_ARGS}`
p_info Make configuration is:
echo "${PKG_MAKE_CONF}" | sed 's/^/## /'

# HACK: install our own ports _inside_ the normal ports dir
cp -fR $WL_PORTSDIR/* $PORTSDIR || exit 1

# Cleanup of old packages
if [ -d "${NANO_PACKAGE_DIR}" ]; then
	p_warn "Deleted all (old) packages at ${NANO_PACKAGE_DIR}"
	rm -R ${NANO_PACKAGE_DIR}/*
fi
p_info Created target dir ${NANO_PACKAGE_DIR}
mkdir -p ${NANO_PACKAGE_DIR}

# Build required packages
MAKE_CONF=`mktemp -t $(basename $0)`
echo "${PKG_MAKE_CONF}" > $MAKE_CONF
MAKE="make __MAKE_CONF=$MAKE_CONF ${PKG_MAKE_ARGS}"
BUILD_LIST=''
set `echo ${PKG_TO_BUILD} | xargs -n1 -I% echo $PORTSDIR/%`
while [ "$1" ]; do
  PACKAGE=$1; shift
  BUILD_LIST="${BUILD_LIST} ${PACKAGE}"

  # Build new one
  LOGFILE="$LOGDIR/build_`echo $PACKAGE | tr '/' '_'`.log"
  echo ""
  p_info Packaging $PACKAGE
  cd $PACKAGE || exit 1

  # Check for build dependencies
  BUILDDEP_PKG=`${MAKE} build-depends-list | awk -F: '{print $2}'`
  if [ -n "${BUILDDEP_PKG}" ]; then
	  p_info Build dependencies needed are:
          p_info `p_list ${BUILDDEP_PKG}`
  fi

  # Check for run dependencies
  PKGDEP_PKGS=`${MAKE} package-depends-list | awk '{print $2}'`
  if [ -n "${PKGDEP_PKGS}" ]; then
	  p_info Package dependencies also packaged are:
	  p_info `p_list ${PKGDEP_PKGS}`
  fi

  PKGNAME=`${MAKE} extract-message | awk '{print $NF}'`
  PKGBUILDLOG=/tmp/build.$$.`basename $PACKAGE`.log
  p_info Packaging $PACKAGE ... details at $PKGBUILDLOG
  ${MAKE} PACKAGES=/root/nanobsd/pkg clean package do-package 1>>$PKGBUILDLOG 2>>$PKGBUILDLOG
  if [ $? -ne 0 ]; then
    p_err "Failed to create $PKGNAME"
    exit 1
  fi

  p_info Checking dependencies
  for PKG in $PKGDEP_PKGS; do
     echo "${BUILD_LIST}" | grep -q "$PKG"
     if [ $? -eq 0 ]; then
       # Already packaged
       p_info ${PKG} Already packaged
     else
       echo $@  | grep -q "${PKG}"
       if [ $? -eq 0 ]; then
          p_info ${PKG} Already planned
       else
          set $@ ${PKG}
       fi
     fi
  done
  p_info Packaging $PACKAGE succesfull
done
  
p_info `echo ${BUILD_LIST} | wc -w` packages build succesfully

if [ ${DEBUG} -eq 0 ]; then
  rm -R ${LOGDIR}
else
  p_info Debugging enabled ${LOGDIR} saved
fi

# House keeping
rm $MAKE_CONF

