#!/bin/bash


if [[ $OSTYPE == *darwin* ]] ||  [[ $OSTYPE == *linux* ]] ; then
	if test -d COIN-OS ; then 
		echo "COIN-OS exists"
		cd COIN-OS
		make clean
		cd ..
	else
		echo "downloading COIN-OS" 
		if ( svn co  https://projects.coin-or.org/svn/OS/releases/2.3.5 COIN-OS ) ; then
			echo "Finished - download COIN-OS"	
			echo "Downloading GLPK" 
			cd COIN-OS/ThirdParty/Glpk/
			./get.Glpk
			cd ../../../
			echo "Finished - download GLPK"
		else
			echo "Can't download COIN-OS - download COIN-OS"	
		fi
	fi
fi

if test -d COIN-OS ; then 
	
	cd COIN-OS
	confErg=0;
	if [[ $OSTYPE == *darwin* ]]; then
		if (./configure COIN_SKIP_PROJECTS="Ipopt Bonmin Bcp DyLP Couenne HSL" ADD_CXXFLAGS="-mmacosx-version-min=10.4" ADD_CFLAGS="-mmacosx-version-min=10.4" ADD_FFLAGS="-mmacosx-version-min=10.4" LDFLAGS="-flat_namespace" --enable-static --disable-shared --enable-cbc-parallel ); then
			confErg=1;
		fi
	else
		if ( ./configure COIN_SKIP_PROJECTS="Ipopt Bonmin Bcp DyLP Couenne HSL" --enable-static --disable-shared --enable-cbc-parallel ) ; then 
			confErg=1;
		fi
	fi	
		
	if  [ $confErg = 1 ]
    then
		echo "configure finished"
    else
		echo "Configure failed"
        exit 1
    fi

    make
    make install
	
	if test -d ThirdParty/Glpk/glpk ; then 
    	cd ThirdParty/Glpk/glpk
    	if ./configure --disable-shared
    	then
       		make 
        	cd examples
        	cp glpsol ../../../../bin/glpsol
    	else
        	echo "GLPK configure failed"
        	cd ../../../
        	exit 3
    	fi
    	cd ../../../../
    fi
    
    if [[ $OSTYPE == *msys* ]] ; then
    	cd bin
    	cpFile=`which libstdc++-6.dll`
    	cp $cpFile .
    	cpFile=`which mingwm10.dll`
    	cp $cpFile .
    	cpFile=`which libgcc_s_dw2-1.dll`
    	cp $cpFile .
    fi
    
	echo "COIN-OS was built in COIN-OS/bin"
	
else
    echo "COIN-OS does not exists"
    exit 1
fi
