#!/bin/sh

set -e

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

#BUILD=${BUILD:-1}
BUILD=0

DEBS="
libsdl-net1.2
libsdl-mixer1.2
libsdl1.2debian-alsa
libsdl1.2-dev
libdirectfb-0.9-25
"

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.txt

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 --allow-unauthenticated -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"

######################################################################
# Sources

# Fetch sources for all debs

for DEB in $DEBS; do
    # Filter out debs in local/pkgs
    if [ -e local/pkgs/${DEB}_*.deb ]; then
	# Make sure we don't ship an old version
        if VER=$($APT_CACHE 2>/dev/null show $DEB | grep-dctrl "" -n -s Version); then
            VER2=$(dpkg -I local/pkgs/${DEB}_*.deb | grep "^ Version:" | cut -b11-)
	    if dpkg --compare-versions "$VER" ">=" "$VER2"; then
		echo >&2 "$DEB has older version in local than in Debian!"
		exit 1
	    fi
	    echo >&2 "$DEB has newer version in local than in Debian"
	fi
    else
	# Deb needs fetching
        echo $DEB
    fi
done \
| xargs $APT_CACHE show \
| grep-dctrl "" -s Package,Version,Source \
| while read KEY VAL; do # ^ Get package information, needed fields and parse
    # Source: is optional and may not contain a version
    # Fill in missing information from Package and Version
    case "$KEY" in
      Package:) PKG="$VAL"; SRC="$VAL";;
      Version:) VER="$VAL";;
      Source:) case "$VAL" in
		 *\(*\)) SRC=$(echo "$VAL" | cut -d" " -f1)
			 VER=$(echo "$VAL" | sed 's/.*(\(.*\))/\1/');;
		 "") ;;
		 *) SRC="$VAL";;
	       esac;;
      "") echo >&2 "Fetching source $SRC $VER for $PKG"
	  echo "$SRC=$VER";;
    esac
  done \
| sort -u | (cd srcs; xargs $APT_GET -d source) # Fetch source

######################################################################
# Debs

if [ "$BUILD" = 1 ]; then
    # Build all debs from source
    cd build
    for DSC in ../srcs/*.dsc; do
      PKG=$(basename $DSC | cut -d_ -f1)
      echo $PKG
      dpkg-source -sn -x $DSC
      cd $PKG-*
      dpkg-buildpackage -rfakeroot -uc -us -B
      cd ..
      #rm -rf $PKG
    done
    cd ..
else
    # Or fetch prebuild debs
    for pkg in $DEBS; do
        if [ -e local/pkgs/${pkg}_*.deb ]; then
            (cd build; ln -s ../local/pkgs/${pkg}_*.deb .)
        else
	    echo $pkg
        fi
    done | xargs $APT_GET --download-only install
    cp $APTDIR/cache/archives/*.deb build/
fi

# Move only the wanted debs out of build and clean up
for pkg in $DEBS; do
  mv build/${pkg}_*.deb pkgs/
done
rm -rf $APTDIR build

# Sanity check that we have _matching_ source for every deb.
# With debs in local this can happen.

dpkg-scanpackages pkgs /dev/null 2>/dev/null \
| grep-dctrl "" -s Package,Version,Source \
| while read KEY VAL; do
    case "$KEY" in
      Package:) PKG="$VAL"; SRC="$VAL";;
      Version:) VER="$VAL";;
      Source:) case "$VAL" in
		 *\(*\)) SRC=$(echo "$VAL" | cut -d" " -f1)
			 VER=$(echo "$VAL" | sed 's/.*(\(.*\))/\1/');;
		 "") ;;
		 *) SRC="$VAL";;
	       esac;;
      "") echo "Testing source $SRC $VER for $PKG"
	  FVER=$(echo "$VER" | cut -d: -f2)
	  if [ ! -e "local/srcs/${SRC}_${FVER}.dsc" ]; then
	    if [ ! -e "srcs/${SRC}_${FVER}.dsc" ]; then
	      echo "Missing source $SRC $VER for $PKG!"
	      exit 1
	    fi
	  fi;;
    esac
  done

echo All sources fetched, all packages build or fetched, all versions match.
echo Enjoy.
exit 0
