#!/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=$(pwd)/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

# detect jemalloc for faster memory allocation
# disable for legacy arch builds (same as include.mk)
jemallocLib=""
if [ -z ${CACTUS_LEGACY_ARCH+x} ]; then
    if pkg-config --exists jemalloc 2>/dev/null; then
        jemallocLib="-ljemalloc -lm"
    elif [ -f "$(pwd)/lib/libjemalloc.a" ]; then
        jemallocLib="-L$(pwd)/lib -ljemalloc -lm"
    fi
fi

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

# maf_stream
cd ${mafBuildDir}
wget -nv --tries=5 --waitretry=3 --timeout=60 --retry-connrefused 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 -nv --tries=5 --waitretry=3 --timeout=60 --retry-connrefused https://github.com/samtools/samtools/releases/download/1.23/samtools-1.23.tar.bz2
tar --no-same-owner -xf samtools-1.23.tar.bz2
cd samtools-1.23
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.23
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 fd0e04b501ed3d90dffe91a93801a7a7545f2147
git submodule update --init --recursive
export HALDIR=${CWD}/submodules/hal
LIBS="${jemallocLib} -llz4 -lzstd" 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 46479b60592c22708abfa6ed901d9d6ecf10d395
find . -name "*.mk" | xargs sed -ie "s/-Werror//g"
find . -name "Makefile*" | xargs sed -ie "s/-Werror//g"
# hack in flags support
sed -ie 's/cflags =/cflags = ${CFLAGS}/g' inc/common.mk
# and sonLib path
sed -ie  "s#sonLibPath = .*#sonLibPath = ${CWD}/submodules/sonLib/lib#g" inc/common.mk
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
