#!/bin/sh
#---------------------------------------------------------------
# Module          : bin
# File            : cooker.sh
# Version         : $Id: cooker.sh,v 1.2 2006/08/09 04:55:10 fred Exp $
# Author          : Frederic Lepied
# Created On      : Sat May 27 18:22:42 2006
# Purpose         : build a package from cooker
#---------------------------------------------------------------

set -e

if [ $# -eq 0 -o $# -gt 3 ]; then
    echo "Usage: $0 [-s] <name> [<directory>]" 1>&2
    echo "Download an src.rpm from Mandriva Linux cooker and build it on the local system." 1>&2
    echo "If -s is used only download the file." 1>&2
    echo "If <directory> is specified, save the resulting files in the target directory." 1>&2
    exit 1
fi

if [ $1 = -s ]; then
    sourceonly=1
    shift
else
    sourceonly=
fi

URL=ftp://ftp.free.fr/mirrors/ftp.mandriva.com/MandrivaLinux/devel/cooker/SRPMS
t=`mktemp`
d=`mktemp -d`

mv $t $t.src.rpm
t=$t.src.rpm

clean() {
    echo "cleaning"
    rm -f $t
    rm -rf $d
}

trap clean 0

wget -q -O $t $URL/main/release/$1*.src.rpm

if [ ! -s $t ]; then
    echo "trying from contrib"
    wget -q -O $t $URL/contrib/release/$1*.src.rpm
fi

if [ ! -s $t ]; then
    echo "unable to download $1" 1>&2
    exit 1
fi

if [ "$sourceonly" = 1 ]; then
    name="`rpm -qp --qf '%{NAME}-%{VERSION}-%{RELEASE}.src.rpm' $t`"
    mv $t "$name"
    echo "$name downloaded"
    exit 0
fi

echo "$1 downloaded to $t"

sudo /usr/sbin/urpmi --auto $t

rpm2 $d -i $t

set +e
trap "" 0
rpm -ba $d/SPECS/*.spec

if [ $? = 0 ]; then
    trap clean 0
    sudo /usr/sbin/urpmi $d/RPMS/*/*.rpm
else
    rpm -bs --nodeps $d/SPECS/*.spec
    echo "Unable to build the package. Look into $d to solve the pb" 1>&2
    rm -f $t
    exit 1
fi

if [ -d "$2" ]; then
    mv $d/SRPMS/*.rpm $d/RPMS/*/*.rpm "$2"
fi

# cooker.sh ends here
