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

## Build Variables
bioconda_name=aquamis
bioconda_latest=$(mamba search $bioconda_name | grep -P "^${bioconda_name}" | sort --key=2 | tail -n1)
bioconda_version=$(awk '{print $2}' <<< "$bioconda_latest")
bioconda_build=$(awk '{print $3}' <<< "$bioconda_latest")
biocontainer="quay.io/biocontainers/${bioconda_name}:${bioconda_version}--${bioconda_build}"
target_container="bfrbioinformatics/${bioconda_name}:${bioconda_version}-biocontainer"

## Pull the latest version of the image, in order to populate the build cache:
docker pull $biocontainer || true
docker pull $target_container || true

## Build the application stage, using cached databases & testdata stage:
echo "Building $target_container" | tee -a $script_path/build_biocontainer.log
printf -v buildbegin '%(%Y-%m-%d %H:%M:%S)T' -1
docker buildx build  \
  --file $script_path/Dockerfile  \
  --target biocontainer  \
  --cache-from=$biocontainer  \
  --cache-from=$target_container  \
  --build-arg BIOCONTAINER=$biocontainer  \
  --build-arg BIOCONDA_VERSION=$bioconda_version  \
  --build-arg BIOCONDA_BUILD=$bioconda_build  \
  --build-arg BUILD_DATE=$(date +"%Y%m%d%H%M%S")  \
  --tag $target_container  \
  $script_path |& tee -a $script_path/build_biocontainer.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_biocontainer.log

## Push the new versions:
echo "Pushing $target_container" | tee -a $script_path/build_biocontainer.log
docker push $target_container |& tee -a $script_path/build_biocontainer.log
