#!/bin/bash
set -euo pipefail

GIT_BRANCH="master"
GIT_VERSION=$(grep -P -o '(?<=version = ").*(?=")' ../../aquamis.py)

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

# Build the application stage, using cached databases & testdata stage:
echo "Building bfrbioinformatics/aquamis:conda, e.g. bfrbioinformatics/aquamis:$GIT_VERSION"
buildbegin=$(date +"%Y-%m-%d %H:%M:%S")
docker build --target conda \
       --cache-from=bfrbioinformatics/aquamis:databases \
       --cache-from=bfrbioinformatics/aquamis:testdata \
       --cache-from=bfrbioinformatics/aquamis:conda \
       --build-arg CONDA_ENV_NAME=$(head -1 ../../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:conda .
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 bfrbioinformatics/aquamis:conda, e.g. bfrbioinformatics/aquamis:$GIT_VERSION"
docker push bfrbioinformatics/aquamis:$GIT_VERSION
docker push bfrbioinformatics/aquamis:conda
