#!/bin/sh
#
# This is run in the chroot, so don't run yourself...
#
# Copyright (c) 2006,2008 Bryan L Blackburn.  All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 3. Neither the name Bryan L Blackburn, nor the names of any contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
# AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

if [[ -z "$PREFIX" ]]; then
    PREFIX=/opt/local
fi
TCLSH=${PREFIX}/bin/port-tclsh
if [[ ! -x ${PREFIX}/bin/port-tclsh ]]; then
    TCLSH=/usr/bin/tclsh
fi

function uninstallPorts()
{
   installedPorts=`${PREFIX}/bin/port echo active | /usr/bin/awk '{print $1}'`
   for uninstallPort in $installedPorts; do
      echo "Deactivating $uninstallPort"
      portOutput=`${PREFIX}/bin/port -dvf deactivate $uninstallPort 2>&1`
      if [[ $? != 0 ]]; then
         echo $portOutput
         break
      fi
   done
}


function cleanBuildStuff()
{
   rm -rf ${PREFIX}/var/macports/build/*
   uninstallPorts
   if [[ $? != 0 ]]; then
      echo "Uninstall failed, aborting"
      exit 1
   fi
}


cleanBuildStuff
PORTRESULTSDIR="/var/tmp/portresults"
PROGRESSLOG="/var/tmp/progress.log"
FAILCACHE="/var/tmp/failcache"
rm -rf ${PORTRESULTSDIR}
/bin/mkdir -p ${PORTRESULTSDIR}/success ${PORTRESULTSDIR}/fail

useFailCache=""
if [[ -f /var/tmp/portlist && `head -n1 /var/tmp/portlist` != "all" ]]; then
   portList=`< /var/tmp/portlist $TCLSH /var/tmp/genportlist.tcl -`
else
   portList=`$TCLSH /var/tmp/genportlist.tcl`
   useFailCache=1
fi
/bin/rm -f /var/tmp/portlist

portCount=`echo ${portList} | /usr/bin/wc -w`
portCount=$(($portCount))   # Get rid of wc's spacing

shopt -s extglob

currentCount=1
for portName in ${portList}; do
   trap "echo \"Canceled, cleaning up...\"; cleanBuildStuff" EXIT

   echo "Building ${portName} (${currentCount} of ${portCount})...\c" | tee -a ${PROGRESSLOG}
   # If there's a package, don't build again
   if [[ -f `$TCLSH /var/tmp/archivepath.tcl $portName` ]]; then
      echo "package found, not building again" | tee -a ${PROGRESSLOG} | tee ${PORTRESULTSDIR}/success/${portName}.log
   else
      skipPort=""
      portFile=`${PREFIX}/bin/port file ${portName}`
      if [[ -n "$useFailCache" && ! "$portFile" -nt "${FAILCACHE}/${portName}" ]]; then
         echo "skipping, portfile not modified since last failure" | tee -a ${PROGRESSLOG} | tee ${PORTRESULTSDIR}/fail/${portName}.log
         skipPort=1
      else
         for oneDep in `$TCLSH /var/tmp/dep_ports.tcl $portName`; do
            if [[ -f ${PORTRESULTSDIR}/fail/${oneDep}.log ]]; then
                skipPort=1
                echo "skipping, $oneDep previously failed and is needed" | tee -a ${PROGRESSLOG}
                echo "${portName} not built due to failed dependency $oneDep" > ${PORTRESULTSDIR}/fail/${portName}.log
                break
            fi
         done
      fi
      if [[ -z "$skipPort" ]]; then
         ${PREFIX}/bin/port -dv install $portName | tee ${PORTRESULTSDIR}/${portName}.log 2>&1
         if [[ ${PIPESTATUS[0]} == 0 ]]; then
            /bin/mv ${PORTRESULTSDIR}/${portName}.log ${PORTRESULTSDIR}/success
            echo "success" | tee -a ${PROGRESSLOG}
            rm -f ${FAILCACHE}/${portName}
         else
            /bin/mv ${PORTRESULTSDIR}/${portName}.log ${PORTRESULTSDIR}/fail
            echo "failure" | tee -a ${PROGRESSLOG}
            ${PREFIX}/bin/port clean --work $portName rdepof:${portName}
            touch -r ${portFile} ${FAILCACHE}/${portName}
         fi
         uninstallPorts
         if [[ $? != 0 ]]; then
            echo "Uninstall failed, aborting"
            exit 2
         fi
      fi
   fi
   currentCount=$((${currentCount}+1))
done

trap "" EXIT

cleanBuildStuff

exit 0

