#!/bin/bash
#
# Copyright 2004 Todd Kulesza
#
# The Dropline GNOME Installation System is free software.
# You can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
#

# ${DLG_ROOT} should be the root directory of the Dropline Build System.
# This only needs to be set if you try to run ./build from outside of
# the root directory.
#DLG_ROOT=/usr/src/dropline-build-system

export DLG_ROOT=${DLG_ROOT:-`pwd`}

. ${DLG_ROOT}/SCRIPTS/dropline-header
#DLG_SCRIPTDIR=$DLG_ROOT/SCRIPTS

show_usage ()
{
    echo "Usage:"
    echo " $0 <packages>"
    echo " $0 -meta <meta-package>"
    echo ""
    echo "Note: Package definitions in the SCRIPTS-\$DLG_OTHERVERSION directory"
    echo "will only be used if the environment variable DLG_OTHERVERSION is"
    echo "actually set to something non-null."
	
    die
}

if [ -z "$1" ]; then
    show_usage
fi

build_package ()
{
    if [ $# != "1" ]; then
	return
    fi

    NAME=${1}

    if [ -n "$DLG_OTHERVERSION" -a -d $DLG_SCRIPTDIR-$DLG_OTHERVERSION/$NAME ]; then
      echo "*** ALPHA TESTER MODE ENABLED ***"
      DESC="$DLG_SCRIPTDIR-$DLG_OTHERVERSION/$NAME/desc"  
      BUILD="$DLG_SCRIPTDIR-$DLG_OTHERVERSION/$NAME/build"  
    else
      DESC="${DLG_SCRIPTDIR}/${NAME}/desc"
      BUILD="${DLG_SCRIPTDIR}/${NAME}/build"
    fi

    if [ ! -e ${DESC} ]; then
	die "Error: Could not find desc file for ${NAME}."
    fi

    if [[ ! -e ${BUILD} && ! -e ${BUILD}.user ]]; then
	die "Error: Could not find a build file for ${NAME}."
    fi

    if [ -f ${BUILD}.user ]; then
	echo "Using user's build script for package $NAME"
	sh ${BUILD}.user || die "Failed package $NAME"
    else
	echo "Using Dropline's build script for package $NAME"
	sh ${BUILD} || die "Failed package $NAME"
    fi
}

build_meta ()
{
    if [ $# != "1" ]; then
	return
    fi

    META=${1}
    LIST="${DLG_METADIR}/${META}"

    if [ ! -f ${LIST} ]; then
	die "Error: Could not find list file for ${META}."
    fi

    echo "Building meta-package $META"

    for PKG in $(cat ${LIST} | grep -v "^#")
    do
      build_package $PKG
      echo "Installing/Upgrading $PKG"
      upgradepkg --reinstall --install-new \
	  ${DLG_PACKAGEDIR}/$PKG*.tgz
    done

    echo "Finished meta-package $META"
}

if [[ "$1" == "-meta" || "$1" == "-m" ]]; then
    build_meta $2
else
    for PKG in $@
    do
      build_package $PKG
    done
fi
