#!/bin/sh
#
# Queue up a port for a tinderbox run.
# For each $BUILD defined add "dir/port" to the tinderbox queue.
# It makes sure "dir/port" exists inside $PORTSDIR first.
#
# TODO:
# Handle -h (show usage) and any other options?
# Handle putting stuff in ${TBROOT}/scripts/etc/env/portstree.foo
# Handle setting all possible OPTION combinations
# Handle error checking (does the directory exist for the ports tree used)
# Handle multiple ports trees being defined
# Handle setting builds to NOT include (ie: remove from the default list)
#
# -- WXS
# wxs@FreeBSD.org

usage() {
	echo ""
	echo "$0 [port dir] [port dir] ... [port dir]"
	echo "If 'port dir' is ommitted the current directory is used."
	echo "If $$PWD is '/home/foo/ports/devel/git' then 'devel/git' is used."
	echo ""
	exit 1
}

addToQueue() {
	#echo "adding ${PORT}"
	for BUILD in ${BUILDS}; do
		${TBROOT}/tc addBuildPortsQueueEntry -b ${BUILD} -d ${PORT} ${USRNAME}
	done
}

#if [ $(id -u) != 0 ]; then
#	echo "Must be root to run this."
#	exit 1
#fi

# Set some defaults if they are not already defined.
# We build for all available builds by default.
# If you want to build against only a subset of builds
# then set ${BUILDS} in your environment.
if [ ! -d "${TBROOT}" ]; then
	TBROOT=/tinderbox/scripts
fi

if [ -z "${PORTSDIR}" -a ! -d "${PORTSDIR}" ]; then
	PORTSDIR=/usr/ports
fi

if [ -z "${BUILDS}" ]; then
	BUILDS=$($TBROOT/tc listBuilds)
fi

# Get the UID and the corresponding username.
UID=$(id -u)
USERNAME=$(pw user show ${UID} | cut -d: -f1)
if [ $(pw user show ${USERNAME} | cut -d: -f3) != ${UID} ]; then
	USRNAME=""
else
	USRNAME="-u ${USERNAME}"
fi

PORTSDIR="$(realpath ${PORTSDIR})"
DIR="$(realpath ${PWD})"

if [ $# -eq 0 ]; then
	PORT="${DIR##${PORTSDIR}/}"
	addToQueue
else 
	while [ $# -ge 1 ]; do
		PORT=$1
		addToQueue
		shift
	done
fi
