#!/usr/bin/env bash

# Building scBayes
# ----------------
# 
# This script attempts to automatically download and build scBayes and
# its dependencies, which includes
# [htslib](https://github.com/samtools/htslib),
# [yaml-cpp](https://github.com/jbeder/yaml-cpp), and scBayes itself. Note that
# a c++ compiler with c++14 standard support is necessary.
# 
# The script will first create a directory `build`, in which all downloading
# and compilation will take place. If any error were to occur and you wish to
# try again, you can simply delete the entire directory. Another directory
# `local`inside the current directory will contain the final libraries and
# binaries. The two components of scbayes can be found at
# `local/bin/scGenotype` and `local/bin/scAssign`.

ROOTDIR=$(pwd)
BUILD_DIR=$ROOTDIR/build
INSTALL_DIR=$ROOTDIR/local

if command -v wget >/dev/null; then
    FETCH_CMD="wget -c"
elif command -v curl >/dev/null; then
    FETCH_CMD="curl -sLO"
else
    echo "cannot find either wget or curl. cannot build..."
    exit 1
fi

function check_prog {
    if ! command -v $1 > /dev/null; then
        echo "cannot find $1"
        exit 1
    fi
}

function setup_dirs {
    mkdir -p $BUILD_DIR
    mkdir -p $INSTALL_DIR
}

function build_htslib {
    cd $BUILD_DIR
    $FETCH_CMD https://github.com/samtools/htslib/releases/download/1.9/htslib-1.9.tar.bz2
    tar -xf htslib-1.9.tar.bz2
    cd htslib-1.9
    ./configure --disable-bz2 --disable-lzma --prefix=$INSTALL_DIR
    make && make install
    cd $ROOTDIR
}

function build_yaml_cpp {
    cd $BUILD_DIR
    $FETCH_CMD https://github.com/jbeder/yaml-cpp/archive/yaml-cpp-0.6.2.tar.gz
    tar -xf yaml-cpp-0.6.2.tar.gz
    cd yaml-cpp-yaml-cpp-0.6.2
    mkdir build
    cd build
    cmake -DCMAKE_INSTALL_PREFIX=$INSTALL_DIR ..
    make && make install
    cd $ROOTDIR
}

function build_scbayes {
    cd $BUILD_DIR
    git clone --recursive https://gitlab.com/yiq/scbayes
    cd scbayes
    ./configure --with-htslib=$INSTALL_DIR --with-yaml-cpp=$INSTALL_DIR --prefix=$INSTALL_DIR
    make && make install
}

check_prog cmake
check_prog make
check_prog git

setup_dirs
build_htslib
build_yaml_cpp
build_scbayes
