#!/bin/bash
set -euo pipefail

GIT_SEARCH=$(conda search aquamis | grep -P "^aquamis" | sort --key=2 | tail -n1)
BIOCONDA_VERSION=$(echo $GIT_SEARCH | awk '{print $2}')
BIOCONDA_BUILD=$(echo $GIT_SEARCH | awk '{print $3}')
BIOCONDA_CONTAINER="quay.io/biocontainers/aquamis:${BIOCONDA_VERSION}--${BIOCONDA_BUILD}"
TARGET_CONTAINER="bfrbioinformatics/aquamis:${BIOCONDA_VERSION}.bioconda"

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

# Build the application stage, using cached databases & testdata stage:
echo "Building bfrbioinformatics/aquamis:${BIOCONDA_VERSION}.bioconda"
buildbegin=$(date +"%Y-%m-%d %H:%M:%S")
docker build --target bioconda \
  --cache-from=bfrbioinformatics/aquamis:databases \
  --cache-from=bfrbioinformatics/aquamis:testdata \
  --cache-from=$BIOCONDA_CONTAINER \
  --cache-from=$TARGET_CONTAINER \
  --build-arg BIOCONDA_CONTAINER=$BIOCONDA_CONTAINER \
  --build-arg BIOCONDA_VERSION=${BIOCONDA_VERSION} \
  --build-arg BUILD_DATE=$(date +"%Y%m%d%H%M%S") \
  --tag $TARGET_CONTAINER .
buildfinish=$(date +"%Y-%m-%d %H:%M:%S")

# Build duration on Gandalf: 6 min 30 sec
echo "Building time from $buildbegin till $buildfinish"

# Push the new versions:
echo "Pushing $TARGET_CONTAINER"
#docker push $TARGET_CONTAINER

# TODO: Bioconda is based on BusyBox which does not support the Snakemake rule "Software Versions" functions $(whereis) and the grep Perl regex "-P"