#!/bin/sh

set -e

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

BUILD=${BUILD:-0}

# DEBS that we do not want in Ubuntu due to being in universe and/or
# obsolescence:
# libesd0 # -> provided by libesd-alsa0
# libglib1.2
# libgtk1.2
# libgtk1.2-common
# gdk-imlib1
# gdk-imlib11
# libfusionsound-0.9-25
# libglu1-xorg
# libstdc++2.10-glibc2.2
# libstdc++2.9-glibc2.1
# libstdc++3
# libsvga1
# lesstif2

DEBS="at-spi
coreutils
freeglut3
gcc-4.2-base
gtk2-engines
gtk2-engines-murrine
gtk2-engines-pixbuf
gtk2-engines-ubuntulooks
libacl1
libaio1
libao2
libart-2.0-2
libartsc0
libasound2
libasound2-plugins
libatk1.0-0
libatspi1.0-0
libattr1
libaudio2
libaudiofile0
libbonobo2-0
libbonobo2-common
libbluetooth2
libbz2-1.0
libcap1
libcapi20-3
libc6
libc6-dev
libcairo2
libcomerr2
libcroco3
libcupsimage2
libcupsys2
libdb4.3
libdb4.6
libdbus-1-3
libdirectfb-1.0-0
libdrm2
libesd-alsa0
libexif12
libexpat1
libflac8
libflashsupport
libfontconfig1
libfreetype6
libgail-common
libgail18
libgcc1
libgconf2-4
libgcrypt11
libgl1-mesa-dri
libgl1-mesa-glx
libglade2-0
libglib2.0-0
libglu1-mesa
libgnomecanvas2-0
libgnutls13
libgpg-error0
libgphoto2-2
libgphoto2-port0
libgsf-1-114
libgtk2.0-0
libhal1
libice6
libidl0
libidn11
libieee1284-3
libjack0
libjpeg62
libkeyutils1
libkrb53 
liblcms1
libldap-2.4-2
libltdl3
liblzo1
liblzo2-2
libncurses5
libnss-ldap
libogg0
libopenal0a
libopencdk10
liborbit2
libpam0g
libpam-ldap
libpango1.0-0
libpcre3
libpixman-1-0
libpng12-0
libpopt0
libpulse0
libpulse-browse0
libpulse-mainloop-glib0
libpulsecore5
libqt4-core
libqt4-gui
librsvg2-common
librsvg2-2
libsamplerate0
libsane
libsasl2-2
libsdl-mixer1.2
libsdl-net1.2
libsdl-ttf2.0-0
libsdl1.2-dev
libsdl1.2debian-alsa
libselinux1
libsepol1
libsigc++-2.0-0c2a
libsm6
libsndfile1
libssl0.9.8
libstdc++5
libstdc++6
libtasn1-3
libtiff4
libusb-0.1-4
libwmf0.2-7
libx11-6
libxau6
libxaw7
libxcb-xlib0
libxcb1
libxcomposite1
libxcursor1
libxdamage1
libxdmcp6
libxext6
libxfixes3
libxft2
libxi6
libxinerama1
libxml2
libxmu6
libxmuu1
libxp6
libxpm4
libxrandr2
libxrender1
libxslt1.1
libxss1
libxt6
libxtrap6
libxtst6
libxv1
libxxf86vm1
linux-libc-dev
pulseaudio-utils
unixodbc
xaw3dg
xbitmaps
xcursor-themes
zlib1g
"

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

if [ -d pkgs/.svn ]; then
  mv pkgs/.svn pkgs.svn
fi
rm -rf pkgs
mkdir pkgs
if [ -d pkgs.svn ]; then
  mv pkgs.svn pkgs/.svn
fi

if [ -d srcs/.svn ]; then
  mv srcs/.svn srcs.svn
fi
rm -rf srcs
mkdir srcs
if [ -d srcs.svn ]; then
  mv srcs.svn srcs/.svn
fi

rm -rf build
mkdir build

LIST=sources.list.deb
if [ -e sources.list.local ]; then
  LIST=sources.list.local
fi

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

# Probe apt version for --allow-unauthenticated
APT_VER=$(apt-get --version | head --lines 1 | cut -d" " -f2)
if dpkg --compare-versions "$APT_VER" ">=" 0.6; then
  # Sid apt needs authentication
  APT_AUTH="--allow-unauthenticated"
fi

APT_GET="$APT_GET $APT_AUTH -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=$(echo "$VAL" | sed 's/+b[0-9]*$//');;
      Source:) case "$VAL" in
		 *\(*\)) SRC=$(echo "$VAL" | cut -d" " -f1)
			 VER=$(echo "$VAL" | sed 's/.*(\(.*\))/\1/' | sed 's/+b[0-9]*$//');;
		 "") ;;
		 *) SRC="$VAL";;
	       esac;;
      "") echo >&2 "Fetching source $SRC $VER for $PKG"
	  if [ "$SOURCE_VER_MISMATCH" ]; then
	      echo "$SRC"
	  else
	      echo "$SRC=$VER"
          fi
	  ;;
    esac
  done \
| sort -u | (cd srcs; xargs $APT_GET -d source) || exit 1 # 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="$(echo "$VAL" | sed 's/+b[0-9]*$//')";;
      Source:) case "$VAL" in
		 *\(*\)) SRC=$(echo "$VAL" | cut -d" " -f1)
			 VER=$(echo "$VAL" | sed 's/.*(\(.*\))/\1/' | sed 's/+b[0-9]*$//');;
		 "") ;;
		 *) 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 || exit 1

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