#!/usr/bin/env bash
#
# Script to prepare a glpk tarball for Sage.  This script is only for the
# package maintainer, not for building glpk during a Sage install.
# WARNING: This script will delete/overwrite files in this directory
# and its subdirectories!
#
# HOW TO MAKE THE TARBALL:
# 1) sage --sh build/pkgs/glpk/spkg-src
#
# needs autotools and sage in your PATH.
#
# AUTHOR: Francois Bissey (May 2016)
# Based on ecl's spkg-src originally authored by J. Demeyer

if [ -z "$SAGE_ROOT" ] ; then
    echo >&2 "Error - SAGE_ROOT undefined ... exiting"
    echo >&2 "Maybe run 'sage -sh'?"
    exit 1
fi

# Exit on failure
set -e

PKGNAME=glpk

cd build/pkgs/$PKGNAME

PKGVERSION=`cat package-version.txt |sed 's/[.]p.*//'`
PKGTARBALL="$SAGE_DISTFILES/$PKGNAME-$PKGVERSION.tar.bz2"

# Remove old cruft
rm -rf $PKGNAME-*

# Download and extract upstream tarball
sage-download-file http://ftp.gnu.org/gnu/$PKGNAME/$PKGNAME-$PKGVERSION.tar.gz |tar xz
cd $PKGNAME-$PKGVERSION

# Some patches are applied here, if they need to be applied before
# running autoconf.
echo "applying patches in $PKGNAME-$PKGVERSION"
for patch in ../patches/src/*.patch; do
    patch -p1 <"$patch"
done

# Remove any unneeded files here.
rm -rf src/zlib

# Run libtool/autotools
libtoolize
autoreconf -ivf

# Remove unneeded files generated by autoconf
rm -rf autom4te.cache

# Make the final tarball and generate checksums
cd ..
tar c $PKGNAME-$PKGVERSION | bzip2 -c >"$PKGTARBALL"
sage --package fix-checksum "$PKGNAME"

# Clean up
rm -rf $PKGNAME-*
