#!/bin/bash
set -euo pipefail

## Locate Self
script_real=$(realpath -P "${BASH_SOURCE[0]}")
script_path=$(dirname $script_real)
script_name=$(basename $script_real)
repo_path=$(dirname $(dirname $script_path))

## Select branch or tag
git_branch="master"
git_version=$(cat $repo_path/VERSION)

## Pull the latest version of the image, in order to populate the build cache:
docker pull bfrbioinformatics/aquamis:databases || true
docker pull bfrbioinformatics/aquamis:latest    || true

## Build the application stage, using cached databases & testdata stage:
echo "Building bfrbioinformatics/aquamis:latest, e.g. bfrbioinformatics/aquamis:$git_version" | tee -a $script_path/build_conda.log
printf -v buildbegin '%(%Y-%m-%d %H:%M:%S)T' -1
docker buildx build  \
  --file $script_path/Dockerfile  \
  --target conda  \
  --progress=plain  \
  --cache-from=bfrbioinformatics/aquamis:databases  \
  --cache-from=bfrbioinformatics/aquamis:latest  \
  --build-arg CONDA_ENV_NAME=$(head -1 $repo_path/envs/aquamis_docker.yaml | cut -d' ' -f2)  \
  --build-arg GIT_BRANCH=$git_branch  \
  --build-arg GIT_SHA1=$(git ls-remote https://gitlab.com/bfr_bioinformatics/AQUAMIS.git --branch $git_branch | awk '{print $1}')  \
  --build-arg BUILD_DATE=$(date +"%Y%m%d%H%M%S")  \
  --tag bfrbioinformatics/aquamis:$git_version  \
  --tag bfrbioinformatics/aquamis:latest  \
  $script_path |& tee -a $script_path/build_conda.log
printf -v buildfinish '%(%Y-%m-%d %H:%M:%S)T' -1

## Build duration on Gandalf: 6 min 30 sec
echo "Building time from $buildbegin till $buildfinish" | tee -a $script_path/build_conda.log

## Push the new versions:
echo "Pushing bfrbioinformatics/aquamis:latest, e.g. bfrbioinformatics/aquamis:$git_version" | tee -a $script_path/build_conda.log
docker push bfrbioinformatics/aquamis:$git_version | tee -a $script_path/build_conda.log
docker push bfrbioinformatics/aquamis:latest | tee -a $script_path/build_conda.log
