#!/bin/bash

if [[ $# > 1 ]] || [[ $# == 1 && $1 != "--run-on-github" ]]; then
    echo -e "Usage: $0 [--run-on-github]\n"
    echo -e "Install NPLinker non-pypi dependencies and databases."
    echo -e "Do execute this command after running 'pip install nplinker'.\n"
    echo -e "Option:\n  --run-on-github: spcify the running is in github actions to avoid permission issues\n"
    exit
elif [[ $# == 1 && $1 == "--run-on-github" ]]; then
    run_on_github=true
else
    run_on_github=false
fi

# Set script to exit immediately if any command fails
set -e

#------------------------------------------------------------------------------
# Creat installation path
#------------------------------------------------------------------------------

# Get python install prefix
if command -v python &> /dev/null; then
    PY_PATH=$(python  -c "import sys; print(sys.prefix)")
elif command -v python3 &> /dev/null; then
    PY_PATH=$(python3 -c "import sys; print(sys.prefix)")
else
    echo "❌ Error: python NOT FOUND"
    exit
fi

# check the path of this script
if [[ $(command -v install-nplinker-deps) != $PY_PATH/bin/install-nplinker-deps ]]; then
    echo "❌ Error: command `install-nplinker-deps` invoked from bad path;"
    echo "Please install nplinker with `pip install nplinker` and then re-run this command."
    exit
fi

# create dependecy install path
cd $PY_PATH
[[ -d nplinker_lib ]] || mkdir nplinker_lib
LIB_PATH=$PY_PATH/nplinker_lib
cd $LIB_PATH
echo -e "✅ NPLinker dependecies and databases will be installed in: $LIB_PATH"
echo -e "⏳ Installation will take about 5 minutes\n"


#------------------------------------------------------------------------------
# Check OS system and package manager
# Not support Windows
#------------------------------------------------------------------------------

if [[ "$OSTYPE" == "linux"* ]]; then
    # detect package manager for Linux
    if command -v apt &> /dev/null; then
        echo -e "✅ Package manager is 'apt'\n"
        if ${run_on_github}; then
            do_install="sudo apt install -y"
        else
            apt update &> /dev/null
            do_install="apt install -y"
        fi
    elif command -v dnf &> /dev/null; then
        echo -e "✅ Package manager is 'dnf'\n"
        do_install="dnf install -y"
    elif command -v yum &> /dev/null; then
        echo -e "✅ Package manager is 'yum'\n"
        do_install="yum install -y"
    else
        echo "Package manager command 'apt' or 'dnf' or 'yum' NOT found."
        exit
    fi
elif [[ "$OSTYPE" == "darwin"* ]]; then
    # install package manager brew for MacOS if not exist
    ! command -v brew &> /dev/null && /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    do_install="brew install"
    echo -e "✅ Package manager is 'brew'\n"
else
    echo "Error: NPLinker is not supported on $OSTYPE system, use linux or MacOS system please."
    exit 0
fi

install_it(){
    echo -e "🔥 Start installing $1 ..."
    $do_install $1
    echo -e "✅ $1 installed successfully\n"
}
#------------------------------------------------------------------------------
# Install base dependencies if not exist
#------------------------------------------------------------------------------
BASE_DEPS="
git
wget
gunzip
unzip
"

for cmd in $BASE_DEPS; do
    if ! command -v $cmd &> /dev/null; then
        install_it $cmd
    fi
done

# install gcc compiler (required by FastTree)
if [[ "$OSTYPE" == "darwin"* ]]; then
  if command -v gcc &> /dev/null; then
      gcc="gcc"
  elif command -v gcc-10 &> /dev/null; then
      gcc="gcc-10"
  else
      brew install gcc@10
      gcc="gcc-10"
  fi
fi

# upgrade pip and setuptools
pip install -q -U pip setuptools

#------------------------------------------------------------------------------
# Install NPLinker dependencies
#------------------------------------------------------------------------------

#--- Install BigScape
## Note: DO NOT pip install bigscape until its modular version
echo "🔥 Start installing BigScape ..."
    [[ -d BiG-SCAPE ]] || git clone https://github.com/medema-group/BiG-SCAPE.git
    cd BiG-SCAPE
    git config --add advice.detachedHead false  # disable advice
    git config pull.ff only
    git checkout master
    git pull
    git checkout a3ea8c5a4ef0abdb3b6b043a0f2657d3d778ca20  # tag v1.1.4
    pip install -q -U -r requirements.txt
    chmod 754 bigscape.py
    chmod 664 domains_color_file.tsv
    chmod 775 Annotated_MIBiG_reference
    ln -sf $LIB_PATH/BiG-SCAPE/bigscape.py $PY_PATH/bin
    cd ..
echo -e "✅ BigScape installed successfully\n"

#--- Install FastTree (not support Windows, required by BigScape)
# http://www.microbesonline.org/fasttree/
echo "🔥 Start installing FastTree ..."
    if [[ "$OSTYPE" == "linux"* ]]; then
        $do_install fasttree
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        wget -q --show-progress http://www.microbesonline.org/fasttree/FastTree.c
        $gcc -DNO_SSE -O3 -finline-functions -funroll-loops -Wall -o $PY_PATH/bin/fasttree FastTree.c -lm
        rm FastTree.c
    fi
echo -e "✅ FastTree installed successfully\n"

#--- Install Hmmer (not support Windows and ARM64, required by BigScape)
# brew hmmer not available ARM64 platform (e.g. Apple silicon)
if ! command -v hmmpress &> /dev/null; then
    install_it hmmer
fi

#--- Prepare Pfam database (required by BigScape)
echo "🔥 Start installing Pfam database ..."
    [[ -e Pfam-A.hmm.gz ]] || wget -q --show-progress ftp://ftp.ebi.ac.uk/pub/databases/Pfam/releases/Pfam34.0/Pfam-A.hmm.gz
    gunzip -f Pfam-A.hmm.gz
    hmmpress -f Pfam-A.hmm
echo -e "✅ Pfam database installed successfully\n"


#--- Install canopus_treemap
echo "🔥 Start installing Canopus"
    pip install -U -q canopus@git+https://github.com/kaibioinfo/canopus_treemap.git
echo -e "✅ Canopus installed successfully\n"


#--- Install SIRIUS
echo "🔥 Start installing Sirius"
    if [[ "$OSTYPE" == "linux"* ]]; then
        wget -q --show-progress https://github.com/boecker-lab/sirius/releases/download/v5.5.5/sirius-5.5.5-linux64-headless.zip
        unzip -q -o sirius-5.5.5-linux64-headless.zip
        ln -sf $LIB_PATH/sirius/bin/sirius $PY_PATH/bin
        rm sirius-5.5.5-linux64-headless.zip
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        wget -q --show-progress https://github.com/boecker-lab/sirius/releases/download/v5.5.5/sirius-5.5.5-osx64-headless.zip
        unzip -q -o sirius-5.5.5-osx64-headless.zip
        ln -sf $LIB_PATH/sirius.app/Contents/MacOS/sirius $PY_PATH/bin
        rm sirius-5.5.5-osx64-headless.zip
    fi
echo -e "✅ Sirius installed successfully\n"


echo -e "✅ 🎉 Successfully installed all NPLinker dependencies and databases!\n"
