#!/bin/bash

#####################################################
# Command Line Interface actev: installation script #
#####################################################

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

usage() {
  echo "usage: install.sh [-h | --help] [--cli-env | -c CLI_ENV_PATH] [--scorer-env | -s SCORER_ENV_PATH] [--all]"
}


# Requirements
python3 -h &> /dev/null
if [[ $? -ne "0" ]]; then
  echo "Python3 is required to install and run the CLI."
  echo "Please install Python3.X >= 3.7 and make sure \`python3 -h\` is working."
  exit 1
fi

# Check that .local/bin path is in $PATH
echo $PATH | grep /.local/bin > /dev/null
EXIT_STATUS=$?

if [ $EXIT_STATUS -ne 0 ];then
  echo "Please add ~/.local/bin to your PATH  before running the script:"
  echo "export PATH=\"${PATH}:${HOME}/.local/bin\""
  exit 1
fi

envs="~/.conda_envs"
cli_env="$envs/cli.env"
scorer_env="$envs/scorer.env"
all=0
force_env=0
while [ "$1" != "" ]; do
  case $1 in
    -c | --cli-env )      shift
                          cli_env=$1
                          ;;
    -s | --scorer-env )   shift
                          scorer_env=$1
                          ;;
    -h | --help )         usage
                          exit
                          ;;
    --all )               all=1
                          ;;
    * )                   usage
                          exit 1
  esac
  shift
done

cd "$DIR/../.."
if [[ -f "environment.yml" ]]; then
  # check conda existence
  conda -h &> /dev/null
  if [[ $? -ne "0" ]]; then
    echo "conda is required to install and run the CLI."
    echo "Please install conda and make sure \`conda -h\` is working."
    exit 1
  fi
  # If `environment.yml` exist, ignoring `requirements.txt`
  conda env create -f environment.yml -p $cli_env 2> /dev/null
  if [[ $? -eq 1 ]]; then
    conda activate $cli_env
    conda env update -f environment.yml -p $cli_env
  else
    # these 2 lines allow us to instantly activate the environment
    conda_script="$(conda shell.bash hook)"
    eval "$conda_script"
    conda activate $cli_env
  fi
  actev -h &> /dev/null
  if [[ "$?" -ne 0 ]]; then
    python3 setup.py develop --prefix $cli_env
  fi

  # Exporting scorer env directory to the CLI shell env
  cd "$(dirname "$0")"
  echo '' >> $DIR/private_src/implementation/utils/actev_cli_environment.env
  echo "SCORER_CONDA_ENV=$scorer_env" >> $DIR/private_src/implementation/utils/actev_cli_environment.env
  # install it
  if [[ "$all" -eq 1 ]]; then
    echo "Installation in progress: ActEV_Scorer"
    bash $DIR/private_src/implementation/validate_execution/install.sh $scorer_env
    echo "Installation done: ActEV_Scorer"
  fi
else
  python3 -m pip install -r requirements.txt
  cd "$(dirname "$0")"
  if [[ "$all" -eq 1 ]]; then
    echo "Installation in progress: ActEV_Scorer"
    bash $DIR/private_src/implementation/validate_execution/install.sh
    echo "Installation done: ActEV_Scorer"
  fi
fi
