#!/usr/bin/env bash

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 src
mkdir src
cd src


### ATLAS ###

ATLAS=atlas3.10.1.tar.bz2

if [ -z "$UPSTREAM_SOURCE_DIRECTORY" ]; then
    tar xjf <( curl -L "http://downloads.sourceforge.net/project/math-atlas/Stable/3.10.1/$ATLAS?r=&ts=1373163744&use_mirror=iweb" )
else
    tar xjf "$UPSTREAM_SOURCE_DIRECTORY/$ATLAS"
fi
if [ ! -d ATLAS ]; then
    echo 'ATLAS directory not in atlas tarball, aborting'
    exit 1
fi


### Lapack ###

LAPACK=lapack-3.4.2.tgz

if [ -z "$UPSTREAM_SOURCE_DIRECTORY" ]; then
    curl -O http://www.netlib.org/lapack/$LAPACK
else
    cp "$UPSTREAM_SOURCE_DIRECTORY/$LAPACK" .
fi
gunzip $LAPACK

### Our archdefs ###

if [ -z "$SAGE_ATLAS_ARCHDEFS_DIR" ]; then
    echo "SAGE_ATLAS_ARCHDEFS_DIR should point to a directory containing the archedef tarballs."
    exit 1
fi

mkdir ARCHS
cp -p "$SAGE_ATLAS_ARCHDEFS_DIR"/*.tar.bz2 ARCHS/

### Our shared library hack ###

cp -rp "$SPKG_ROOT"/patches/ATLAS-lib .
cd ATLAS-lib
mkdir m4
autoreconf -fiv
rm -rf autom4te.cache


### Finished creating the src/ directory

# Make everything writable
cd "$SPKG_ROOT"
chmod -R u+w src
