#!/bin/sh -x
#
# see https://fossil.etoilebsd.net/poudriere/doc/trunk/doc/pkgng_repos.wiki
#
. ./config.sh
. ./common.sh

. ./categories.sh
. ./targets.sh
. ./jailflags.sh

#
# always clean restricted packages
BULKFLAGS="-R"
# determine whether or not to try broken packages
if [ "${TRYBROKEN}" = "true" ]; then
  BULKFLAGS="${BULKFLAGS} -T"
fi
if [ -n "${KEEP_WRKDIRS}" -a "${KEEP_WRKDIRS}" = "true" ]; then
  BULKFLAGS="${BULKFLAGS} -w"
fi

rm -f ${SUBSETS}/all.* || exit 1

#
# set up ports
#
# if needed to delete an existing tree
if [ "${DELETE_PORTS}" = "true" ]; then
  poudriere ports -d -p ${PORTS_SUBDIR} || exit 1
fi
if [ ! -d ${PORTSDIR} ]; then
  poudriere ports -c -m svn+https -B ${PORTS_BRANCH_SPEC} -p ${PORTS_SUBDIR} || exit 1
fi
if [ "${UPDATE_PORTS}" = "true" ]; then
  poudriere ports -u -p ${PORTS_SUBDIR} || exit 1
fi
#
# set up src
#
if [ -n ${CONTROLDIR} ]; then
  mkdir -p ${CONTROLDIR} || exit 1
fi
if [ -n ${JAIL_MK_CONF} ]; then
  touch ${JAIL_MK_CONF} || exit 1
fi
pkgngset=`grep "^WITH_PKGNG=yes" ${JAIL_MK_CONF}` 2> /dev/null
if [ -z "${pkgngset}" ]; then
  echo "WITH_PKGNG=yes" >> ${JAIL_MK_CONF}
fi
#
# only powerpc right now
# echo "WITHOUT_PF=yes" >> ${JAIL_MK_CONF} || exit 1
#
if [ -n "${PATCHNAME}" ]; then
  JAILFLAGS="${JAILFLAGS} -P ${PATCHNAME}"
fi
if [ "${DELETE_SRC}" = "true" ]; then
  poudriere jail -d -j ${JAILNAME} || exit 1
fi
if [ ! -d ${JAILDIR} -o "${UPDATE_SRC}" = "true" ]; then
  poudriere jail -c -j ${JAILNAME} -v ${SRC_VERSION} -a ${ARCH} -m svn ${JAILFLAGS} || exit 1
fi
#
# calculate ports to build
#
cp /dev/null /usr/local/etc/poudriere.d/blacklist
if [ "${USEBLACKLIST}" = "true" ]; then
  ${BINDIR}/prepareblacklist || exit 1
fi
#
if [ -n "${CATEGORIES}" ]; then
  for category in ${CATEGORIES}; do
    echo "(cd $PORTSDIR && find $category -type d -depth 1) > ${SUBSETS}/all.$category"
    (cd $PORTSDIR && find $category -type d -depth 1) > ${SUBSETS}/all.$category || exit 1
    TARGETS="${TARGETS} ${SUBSETS}/all.$category"
  done
fi
#
TMPFILE=/tmp/poudriere_spec.`date "+%Y%m%d%H%M.%S"`
rm -f ${TMPFILE}.tmp
for target in ${TARGETS}; do
  grep -v "^#" $target >> ${TMPFILE}.tmp
done
sort ${TMPFILE}.tmp | uniq > ${TMPFILE}
rm -f ${TMPFILE}.tmp
TARGET=${TMPFILE}
#
poudriere bulk -f ${TARGET} -p ${PORTS_SUBDIR} -j ${JAILNAME} ${BULKFLAGS}
#
echo "current total packages for ${JAILNAME}: "`ls ${PACKAGESDIR}/${PACKAGESSUBDIR}/All | wc -l`
