#!/usr/bin/env bash

VERSION="2.1.1"

if [ $# -ne 0 ]; then
    UPSTREAM_SOURCE_DIRECTORY=$1
    echo "Using tarballs from $UPSTREAM_SOURCE_DIRECTORY instead of downloading"
fi

SPKG_ROOT=`pwd`

set -e
shopt -s extglob

# Remove old sources and download new
rm -rf gd*

URL="https://bitbucket.org/libgd/gd-libgd/downloads"
if [ -z "$UPSTREAM_SOURCE_DIRECTORY" ]; then
    tar xJf <( curl -L "$URL/libgd-$VERSION.tar.xz" )
else
    tar xJf "$UPSTREAM_SOURCE_DIRECTORY/libgd-$VERSION.tar.xz"
fi

# Autoreconf it so that it builds correctly on Cygwin64 and ppc64le
cd libgd-$VERSION
rm -f aclocal.m4 Makefile.in configure
autoreconf -fiv
rm -rf autom4te.cache src/config.hin~
cd $SPKG_ROOT
mv "libgd-$VERSION" src

# Recompress directory
tar cjf libgd-`sed s/[.]p.*// package-version.txt`.tar.bz2 src
