#!/bin/bash

## [Goal] Run this script from remote clients to download the <pipeline>/docker subfolder and retrieve Docker images.
## [Author] Holger Brendebach

## Shell Behaviour
set -Eueo pipefail # to exit immediately, add e

## Functions
colorize() {
  ## Fancy echo
  bold=$(tput bold)
  normal=$(tput sgr0)
  red=$(tput setaf 1)
  green=$(tput setaf 2)
  yellow=$(tput setaf 3)
  blue=$(tput setaf 4)
  magenta=$(tput setaf 5)
  cyan=$(tput setaf 6)
  grey=$(tput setaf 7)
  inverted=$(tput rev)
}

git_sparse_clone() (
  repo_url="$1" local_dir="$2" branch="$3" && shift 3

  git init |& tee $logfile
  git remote add --fetch --no-tags --track $branch --master $branch origin "$repo_url" |& tee $logfile
  git config core.sparseCheckout true

  # Loops over remaining args
  for i; do
    echo "$i" >> .git/info/sparse-checkout
  done
  git pull --quiet --depth=1 origin $branch |& tee $logfile
)

## Settings
pipeline="AQUAMIS"
script_name="get_${pipeline,,}_docker.sh"
target_path=$(pwd)/${pipeline}
logfile=$target_path/docker/${script_name/.sh/.log}

## Main
colorize
[[ -x "$(command -v git)" ]] || ( echo "${red}ERROR:${normal} git Not Detected" && exit 1 )
[[ -x "$(command -v docker)" ]] || ( echo "${red}ERROR:${normal} docker Not Detected" && exit 1 )
mkdir -p $target_path/docker && cd $target_path
git version |& tee $logfile
git_sparse_clone "https://gitlab.com/bfr_bioinformatics/${pipeline}.git" "$target_path" "master" "/docker"
docker version |& tee -a $logfile
docker compose version |& tee -a $logfile
docker buildx version |& tee -a $logfile

## Summary
cat <<- HLP |& tee -a $logfile

Executed ${blue}bash <(curl -s https://gitlab.com/bfr_bioinformatics/${pipeline}/-/raw/docker/docker/get_${pipeline,,}_docker.sh)${normal}

${green}Docker Compose download completed.${normal}

(1) For docker-compose, two shell environment variables need to be set:
${blue}export LOCAL_USER_ID=\$(id -u $USER)${normal}
${blue}export ${pipeline^^}_HOST_PATH=$target_path${normal}   # this is just a dummy path for the ${grey}pull${normal}, replace it before the ${grey}up${normal}

${pipeline} docker images may be ${yellow}downloaded${normal} from DockerHub with the command:
(2.a) ${blue}docker compose --file $target_path/docker/docker-compose.yaml pull${normal}

or ${yellow}build${normal} from scratch via Dockerfiles with the command:
(2.b) ${blue}docker compose --file $target_path/docker/docker-compose.yaml build --progress plain${normal}

This will create the Docker images:
* bfrbioinformatics/${pipeline,,}:latest
* bfrbioinformatics/${pipeline,,}:databases-efsa-20230501

(3) Please continue with the section "From Docker" from the ${pipeline} ReadMe at https://gitlab.com/bfr_bioinformatics/${pipeline}
or run the command start immediately with the command (please update your data location as in (1)):
${blue}docker compose --file $(pwd)/${pipeline}/docker/docker-compose.yaml up -d${normal}

HLP
