#!/bin/sh

set -ex

#
# To just download from the sources listed in sources.list.deb, use
# BUILD=0 ./fetch-and-build .  Else, it will build all the sources.
#

BUILD=${BUILD:-1}

# openoffice.org2-evolution 
# mozilla-openoffice.org
# openoffice.org2-officebean

DEBS="libstlport4.6c2 libaudio2 libart-2.0-2 libstartup-notification0 libportaudio0 libcurl3 libicu34 libneon25 libxmlsec1 libxmlsec1-nss libxmlsec1-openssl libssl0.9.8 libflac7 libkrb53 libldap2 libnspr4 libnss3 libxslt1.1 libwpd8c2a libcomerr2 libgnutls12 libsasl2 libgcrypt11 libgpg-error0 libtasn1-2 libmdbtools libgcj7"

export APTDIR=$(mktemp -d)
mkdir -p $APTDIR

rm -rf pkgs
mkdir pkgs

rm -rf srcs
mkdir srcs

rm -rf build
mkdir build

LIST=sources.list.deb

APT_GET="apt-get --assume-yes \
	-o Dir::Etc::sourcelist=`pwd`/$LIST \
	-o Dir::State=$APTDIR/state \
	-o Debug::NoLocking=true \
	-o Dir::Cache=$APTDIR/cache \
	-o Acquire::Retries=3 \
	-o Apt::Architecture=i386"

# Prepare APTDIR
mkdir -p $APTDIR/state/lists/partial
mkdir -p $APTDIR/cache/archives/partial
echo -n > $APTDIR/state/status
APT_GET="$APT_GET -o Dir::State::Status=$APTDIR/state/status"

$APT_GET update

APT_CACHE="apt-cache \
	-o Dir::Etc::sourcelist=`pwd`/$LIST \
	-o Dir::State=$APTDIR/state \
	-o Debug::NoLocking=true \
	-o Dir::Cache=$APTDIR/cache \
	-o Acquire::Retries=3 \
	-o Apt::Architecture=i386 \
	-o Dir::State::Status=$APTDIR/state/status"


SRCS=""
for i in $DEBS; do
  src=`$APT_CACHE showsrc $i | grep '^Package: ' | head -n 1 | awk '{print $2}'`
  case " $SRCS " in
    *" $src "*) ;;
    *) SRCS="$SRCS $src" ;;
  esac
done

cd srcs
$APT_GET -d source $SRCS
cd ..

if [ "$BUILD" = 1 ]; then
    cd build
    for pkg in $SRCS; do
    echo $pkg
      dpkg-source -sn -x ../srcs/${pkg}_*.dsc
      cd $pkg-*
      dpkg-buildpackage -rfakeroot -uc -us -B
      cd ..
      #rm -rf $pk
    done
    cd ..
else
    for pkg in $DEBS; do
        $APT_GET --download-only install $pkg
        cp $APTDIR/cache/archives/${pkg}_*.deb build/
    done
fi

for pkg in $DEBS; do
  mv build/${pkg}_*.deb pkgs/
done

rm -rf $APTDIR build

exit 0
