#!/bin/sh
#
# Compile listing of required packages using poudriere and friends
#
# Rick van der Zwet <rick@wirelessleiden.nl>
#

. `dirname $0`/common.inc.sh

cfg_dir=`dirname $0`/../cfg
abs_cfg_dir=`cd $cfg_dir; pwd -P`
poudriere_pkglist_file=${cfg_dir}/wlpkgbuild11_0-default-node-pkglist


packages_initenv() {
	config_dir=`dirname $0`

	# Install required deamons
	pkg install -y poudriere dialog4ports portshaker

	# Setup poudriere build environment
	poudriere jail -c -j wlpkgbuild11_0 -v 11.0-RELEASE -a i386

	# Setup portshaker
	cp ${config_dir}/portshaker.conf /usr/local/etc/
	cp ${config_dir}/portshaker.d/* /usr/local/etc/portshaker.d

	# Update ports
	portshaker -U
	portshaker -M

	# Setup poudriere ports environment
	poudriere ports -c -F -f none -p default -M /usr/local/poudriere/ports/default

	# Distfile cache should be created if it does not exists
	. /usr/local/etc/poudriere.conf
	if [ ! -d "$DISTFILES_CACHE" ]; then
	  mkdir -p $DISTFILES_CACHE
	fi
}

packages_config() {
	# Configure build options
	poudriere options -j wlpkgbuild11_0 -p default -z node ${1:+-c} ${*:- -f ${poudriere_pkglist_file}}
}


packages_refresh() {
	# Install new package (symlink) options
	POUDRIERE_MAKE_CONF_FILE=wlpkgbuild11_0-node-make.conf
	POUDRIERE_OPTIONS=wlpkgbuild11_0-node-options

	# Clean old stuff
	if [ -d "/usr/local/etc/poudriere.d/$POUDRIERE_MAKE_CONF_FILE" ]; then
	  rm -Rf /usr/local/etc/poudriere.d/$POUDRIERE_MAKE_CONF_FILE
        fi

	if [ -d "/usr/local/etc/poudriere.d/$POUDRIERE_OPTIONS" ]; then
	  rm -Rf /usr/local/etc/poudriere.d/$POUDRIERE_OPTIONS
        fi


	ln -s ${abs_cfg_dir}/$POUDRIERE_MAKE_CONF_FILE /usr/local/etc/poudriere.d/$POUDRIERE_MAKE_CONF_FILE
	ln -s ${abs_cfg_dir}/$POUDRIERE_OPTIONS /usr/local/etc/poudriere.d/$POUDRIERE_OPTIONS
}


packages_build() {
	poudriere bulk -j wlpkgbuild11_0 -p default -z node -f ${poudriere_pkglist_file}
}

# Make package list
. $cfg_dir/nanobsd.wleiden
echo $PACKAGE_LIST | tr " " "\n" > ${poudriere_pkglist_file}


if [ "x$1" = "xinitenv" ]; then
	packages_initenv
	packages_refresh
	shift; packages_config
elif [ "x$1" = "xrefresh" ]; then
	packages_refresh
elif [ "x$1" = "xconfig" ]; then
	shift; packages_config $*
elif [ "x$1" = "xrebuild" ]; then
	packages_refresh
	packages_build
elif [ "x$1" = "xbuild" ]; then
	packages_build
else
	echo "Usage $0 <initenv|config|rebuild|build>"
	exit 128
fi
