#!/bin/sh

set -e

mkdir -p build-tree
cd build-tree

apply_patches_in_subdir() {
    local dir="$1"
    shift
    cd $dir
    for patch in "$@"; do
	patch -p1 <$patch
    done
    cd - >/dev/null
}
download_and_patch() {
    local srcpkg="$1"
    shift
    echo "Downloading $srcpkg from the repositories"
    apt-get source $srcpkg
    dir=$(ls -d ${srcpkg}-*)
    if ! test -d $dir; then
	echo "ERROR: Failed to identify source directory for $srcpkg" >&2
	exit 1
    fi
    mv "$dir" "$srcpkg"
    apply_patches_in_subdir "$srcpkg" $@
}

# Wmi
download_and_patch wmi ../../patches/wmi-1.3.16-smbencrypt.patch \
		       ../../patches/wmi-1.3.16-wmis.patch

download_and_patch curl ../../patches/curl-pth-ntlm.patch
download_and_patch freetds ../../patches/freetds-0.91-pth.patch

# Note: SQSH not rebuilt but wrapped

#wget http://ftp.mozilla.org/pub/mozilla.org/firefox/releases/latest-esr/source/firefox-17.0.6esr.source.tar.bz2
#tar xjf firefox-17.0.6esr.source.tar.bz2
#cp ../patches/mozconfig mozilla-esr17/.mozconfig

#download_and_patch iceweasel ../../patches/moz-esr17-pth-test.patch \
#			     ../../patches/moz-esr17-testpatch-nss
#cp ../patches/mozconfig iceweasel-*/
