#!/bin/sh

set -e

# To build from the sources listed in sources.list.deb instead of using
# the binary packages, use BUILD=1 ./fetch-and-build .  Else, it will
# fetch prebuild debs.

BUILD=${BUILD:-0}

DEBS="coreutils
freeglut3
gcc-4.5-base
lesstif2
libacl1
libaio1
libasyncns0
libattr1
libasound2
libaudio2
libaudiofile0
libc6
libc6-dev
libcairo2
libcap2
libcapi20-3
libcomerr2
libcups2
libdbus-1-3
libdirectfb-1.2-9
libdrm2
libesd0
libexif12
libexpat1
libfltk1.1
libfontconfig1
libfreetype6
libgcc1
libgcrypt11
libgl1-mesa-glx
libgl1-mesa-dri
libglu1-mesa
libglu1-xorg
libgnutls26
libgpg-error0
libgphoto2-2
libgphoto2-port0
libgsl0ldbl
libhal1
libsmbios2
libice6
libieee1284-3
libjack0
libcelt0-0
libjpeg62
libkeyutils1
libkrb5support0
libkrb5-3
libk5crypto3
libgssapi-krb5-2
liblcms1
libldap-2.4-2
libltdl7
liblzo2-2
libmad0
libncurses5
libnss-ldap
libpam0g
libpam-ldap
libpng12-0
libpopt0
libpulse0
libsane
libsasl2-2
libselinux1
libsdl1.2debian-alsa
libsigc++-2.0-0c2a
libsm6
libssl0.9.8
libstdc++5
libstdc++6
libsvga1
libtasn1-3
libtiff4
libusb-0.1-4
libuuid1
libvorbis0a
libvorbisfile3
libwmf0.2-7
libwrap0
libx11-6
libx86-1
libxau6
libxaw7
libxcb1
libxcb-render0
libxcb-render-util0
libxcb-shm0
libxcomposite1
libxdamage1
libxdmcp6
libxext6
libxfixes3
libxft2
libxi6
libxinerama1
libxml2
libxmu6
libxmuu1
libxp6
libxpm4
libxrandr2
libxrender1
libxt6
libxtst6
libxv1
libxcursor1
libxslt1.1
libxss1
libxxf86vm1
odbcinst1debian2
unixodbc
xaw3dg
xbitmaps
xcursor-themes
zlib1g
"

# additional packages for Ubuntu
DEBS="$DEBS
at-spi
bluez-alsa
gtk2-engines
gtk2-engines-murrine
gtk2-engines-pixbuf
gtk2-engines-qtcurve
human-theme
gvfs
libcanberra-gtk-module
libcanberra-gtk0
libcanberra0
libtdb1
libao4
libart-2.0-2
libasound2-plugins
libatspi1.0-0
libatk1.0-0
libbonobo2-0
libbonobo2-common
libbluetooth3
libcroco3
libcupsimage2
libcurl3
libdb4.7
libdbus-glib-1-2
libdrm-intel1
libdrm-radeon1
libdrm-nouveau1
libflac8
libgconf2-4
libgdbm3
libglade2-0
libglib2.0-0
libgnomecanvas2-0
libgnome-keyring0
libgail18
libgail-common
libgsf-1-114
libgsm1
libgstreamer0.10-0
libgstreamer-plugins-base0.10-0
libgdk-pixbuf2.0-0
libgtk2.0-0
libgvfscommon0
libidl0
libidn11
libjasper1
libmpg123-0
libsqlite3-0
libnspr4-0d
libnss3-1d
libogg0
libopenal1
liborbit2
libpango1.0-0
libpcre3
libpixman-1-0
libpulse-browse0
libpulse-mainloop-glib0
pulseaudio
libavahi-common3
libavahi-client3
libspeexdsp1
liboil0.3
libqtcore4
libqtgui4
libqt4-dbus
libqt4-network
libqt4-opengl
libqt4-qt3support
libqt4-script
libqt4-scripttools
libqt4-sql
libqt4-svg
libqt4-test
libqt4-webkit
libqt4-xml
libqt4-xmlpatterns
librsvg2-common
librsvg2-2
libsamplerate0
libsdl-mixer1.2
libsdl-image1.2
libpython2.6
libmikmod2
libsmpeg0
libsdl-net1.2
libsdl-ttf2.0-0
libsdl1.2-dev
libsepol1
libsndfile1
libssh2-1
libtalloc2
libudev0
libvorbisenc2
pulseaudio-utils
libx11-xcb1
libxcb-atom1
"

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 --only-source 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

# Pull out the copyright files
cp debian/copyright.header debian/copyright.tmp
COPYRIGHTERROR=0
cd srcs
find ./ -name "*.dsc" | sort | while read src; do
tmpdir=$(mktemp -d)
dpkg-source -x "$src" "$tmpdir/src" >/dev/null 2>&1
if [ -e "$tmpdir/src/debian/copyright" ]; then
    echo "---------------------------------------------------------------" >> ../debian/copyright.tmp
    echo "Copyright for $src" >> ../debian/copyright.tmp
    cat "$tmpdir/src/debian/copyright" >> ../debian/copyright.tmp
else
    # Check for a manually extracted copyright file
    pname=$(echo "$src" | cut -d_ -f1)
    if [ -e "../debian/copyrights/$pname" ]; then
            echo "Using overriden copyright file for $src"
            echo "---------------------------------------------------------------" >> ../debian/copyright.tmp
            echo "Copyright for $src" >> ../debian/copyright.tmp
            cat "../debian/copyrights/$pname" >> ../debian/copyright.tmp
    else
        echo "WARNING: Copyright missing for $src"
        COPYRIGHTERROR=1
    fi
fi
rm -fr $tmpdir
done
cd ..

if [ "$COPYRIGHTERROR" -gt 0 ]; then
    echo "ERROR: Copyright file missing.  Do not upload"
fi

mv debian/copyright.tmp debian/copyright

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