#!/bin/bash

glpkRelease=4.47

if [[ $OSTYPE == *darwin* ]] ||  [[ $OSTYPE == *linux* ]] ; then
	if test -d glpk-${glpkRelease} ; then 
		echo "GLPK exists"
		cd glpk-${glpkRelease}
		make clean
		cd ..
	else
		echo "downloading GLPK" 
		wgetcmd=wget
		wgetcount=`which wget 2>/dev/null | wc -l`
		if test ! $wgetcount = 1; then
  			if [[ $OSTYPE == *darwin* ]] ; then
    			wgetcmd=ftp
  			else
    			exit -1
    		fi
  		fi
  		rm -f glpk*.tar.gz
		$wgetcmd ftp://ftp.gnu.org/gnu/glpk/glpk-${glpkRelease}.tar.gz
		gunzip -f glpk-${glpkRelease}.tar.gz
		tar xf glpk-${glpkRelease}.tar
		rm glpk-${glpkRelease}.tar
	fi
fi
		

if test -d glpk-${glpkRelease} ; then 
	
	cd glpk-${glpkRelease}
	
	make clean
	
	confErg=0;
	
	if (./configure --disable-shared) ; then
		echo "configure finished"
		make
	else 
		echo "Configure failed"
        exit 1
    fi
    
    examples/glpsol -v 2>glpkStdErr
	if  test -s glpkStdErr ;  then
		echo "Can't execute examples/glpsol"
		echo "Build is canceled"
		exit 1
	fi
	
	cd ../..
	
	if [ ! -d Thirdparty ] ; then 
		mkdir Thirdparty
	fi
	
	cd Thirdparty
	if [ ! -d GLPK ] ; then
		mkdir GLPK
	fi 
	cd ..
	
	cp data/glpk-${glpkRelease}/examples/glpsol Thirdparty/GLPK
	
	cp data/glpk-${glpkRelease}/AUTHORS Thirdparty/GLPK
	cp data/glpk-${glpkRelease}/COPYING Thirdparty/GLPK
    
    echo "GLPK was built in Thirdparty/GLPK"
	
else
    echo "Glpk does not exists"
    exit 1
fi
