#!/usr/bin/env bash

# This script must be run from folder SAGE_ROOT. It modifies the file
# python-igraph-0.7.0.tar.gz into python_igraph-0.7.0.tar.gz, and it modifies
# the name of the top folder accordingly.


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

PKG_DIR="$SAGE_ROOT/build/pkgs/python_igraph/"
VERSION=$(cat "$PKG_DIR/package-version.txt")
PYTHONIGRAPH=python-igraph-$VERSION
PYTHONIGRAPHMOD=python_igraph-$VERSION

set -e
shopt -s extglob

if [ -e $SAGE_ROOT/upstream/$PYTHONIGRAPHMOD-$VERSION.tar.gz ]
then
    echo "The modified .tar file already exists."
    exit
fi

# work in a temporary directory
cd $(mktemp -d)

mkdir src
cd src

tar xzf <( curl -L "igraph.org/nightly/get/python/$PYTHONIGRAPH.tar.gz" )

if [ -e $PYTHONIGRAPH ]
then
    mv $PYTHONIGRAPH $PYTHONIGRAPHMOD
    tar -zcf $PYTHONIGRAPHMOD.tar.gz $PYTHONIGRAPHMOD
    mv $PYTHONIGRAPHMOD.tar.gz $SAGE_ROOT/upstream/python_igraph-$VERSION.tar.gz
    echo "Correctly downloaded/modified input file."
else
    echo "Cannot find file $PYTHONIGRAPH.tar.gz."
fi
cd ..
rm -rf src