#!/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

script_path=$(command -v install-nplinker-deps)
expected_path="$PY_PATH/bin/install-nplinker-deps"

if [[ $script_path != $expected_path ]]; then
    echo "❌ Error: command 'install-nplinker-deps' invoked from an incorrect path or enviroment: $script_path"
    echo "Please ensure that it is invoked from the expected path: $expected_path."
    echo "Check your PATH environment variable to correct the execution order of paths."
    exit 1
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
            echo "To use 'apt' command, you need to allow 'sudo apt' by providing your computer password"
            sudo apt update &> /dev/null
            do_install="sudo 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
echo "🔥 Start installing BigScape ..."
    [[ -d BiG-SCAPE ]] || git clone https://github.com/medema-group/BiG-SCAPE.git
    cd BiG-SCAPE
    git reset --hard
    git config --add advice.detachedHead false  # disable advice
    git config pull.ff only
    git checkout master
    git pull
    git checkout 99d07e57882fc5fa6780f8254823fd3d1abf3bc6 # Commits on Jul 21, 2023
    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 ..
    # blob size limit to remove large files left in history
    [[ -d BiG-SCAPE-v2 ]] || git clone -b dev --filter=blob:limit=10m https://github.com/medema-group/BiG-SCAPE.git BiG-SCAPE-v2
    cd BiG-SCAPE-v2
    git config --ad advice.detatchedHead false
    git checkout 99a4c2e4923bb50e175b2e619c2cee0a14918789 # Commits on Jun 14, 2024
    pip install click
    pip install sqlalchemy
    pip install pyhmmer
    pip install tqdm
    chmod 754 bigscape.py
    ln -sf $LIB_PATH/BiG-SCAPE-v2/bigscape.py $PY_PATH/bin/bigscape-v2.py
    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 (required by BigScape)
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"
