#!/bin/bash
# Download and statically build tools needed for MAF processing

# set this to one to make sure everything gets built statically (necessary for binary release)
STATIC_CHECK=$1

set -beEu -o pipefail

mafBuildDir=$(realpath -m build-maf-tools)
binDir=$(pwd)/bin
# just use cactusRootPath for now
dataDir=$(pwd)/src/cactus
CWD=$(pwd)
# works on MacOS and Linux
if [ -z ${numcpu+x} ]; then
	 numcpu=$(getconf _NPROCESSORS_ONLN)
fi

set -x
rm -rf ${mafBuildDir}
mkdir -p ${mafBuildDir}
mkdir -p ${binDir}

# maf_stream
cd ${mafBuildDir}
wget -q https://github.com/ComparativeGenomicsToolkit/maf_stream/releases/download/v0.1/maf_stream
chmod +x maf_stream
if [[ $STATIC_CHECK -ne 1 || $(ldd maf_stream | grep so | wc -l) -eq 0 ]]
then
	 mv maf_stream ${binDir}
else
	 exit 1
fi

# taffy
cd ${mafBuildDir}
wget -q https://github.com/samtools/samtools/releases/download/1.11/samtools-1.11.tar.bz2
tar -xf samtools-1.11.tar.bz2
cd samtools-1.11
SAMTOOLS_CONFIG_OPTS=""
if [[ $STATIC_CHECK -eq 1 ]]
then
	 SAMTOOLS_CONFIG_OPTS="--disable-shared --enable-static"
fi
./configure --without-curses --disable-libcurl --enable-configure-htslib $SAMTOOLS_CONFIG_OPTS
make -j ${numcpu}
cd htslib-1.11
make -j ${numcpu} libhts.a
export HTSLIB_CFLAGS=-I$(pwd)
export HTSLIB_LIBS="$(pwd)/libhts.a -lbz2 -ldeflate -lm -lpthread -lz -llzma -pthread -lpthread"
cd ${mafBuildDir}
git clone https://github.com/ComparativeGenomicsToolkit/taffy.git
cd taffy
git checkout c75ce895b7975e7ac17cb1ce964db3016615de47
git submodule update --init --recursive
export HALDIR=${CWD}/submodules/hal
make -j ${numcpu}
if [[ $STATIC_CHECK -ne 1 || $(ldd bin/taffy | grep so | wc -l) -eq 0 ]]
then
    mv bin/taffy ${binDir}
else
    exit 1
fi

# mafTools
cd ${mafBuildDir}
git clone https://github.com/ComparativeGenomicsToolkit/mafTools.git
cd mafTools
git checkout 0d2a253a528749bad2c6c0179bd15edd8d56adf6
find . -name "*.mk" | xargs sed -ie "s/-Werror//g"
find . -name "Makefile*" | xargs sed -ie "s/-Werror//g"
# hack in flags support
sed -i inc/common.mk -e 's/cflags =/cflags = ${CFLAGS}/g'
# and sonLib path
sed -i inc/common.mk -e "s#sonLibPath = .*#sonLibPath = ${CWD}/submodules/sonLib/lib#g"
make
for mt in `ls bin/maf*`; do
	 if [[ $STATIC_CHECK -ne 1 || $(ldd ${mt} | grep so | wc -l) -eq 0 ]]
	 then
		  mv ${mt} ${binDir}
	 else
		  exit 1
	 fi
done


cd ${CWD}
rm -rf ${mafBuildDir}

set +x
