#!/bin/bash
#
# This script build the base docker image and the full docker image for LINC.
# It is inspired by the way the docker images are built in the CI/CD pipeline
# (described in the `.gitlab-ci.yml` file).

set -euo pipefail

SCRIPT_DIR=$(cd "$(dirname "${0}")" && pwd)
REPO_ROOT="$(git rev-parse --show-toplevel)"

echo "Determining version information ..."
eval $(${SCRIPT_DIR}/fetch_commit_hashes.sh | tee commits.txt)

BASE_NAME=linc-base
BASE_TAG=$(sha256sum commits.txt | cut -d" " -f1)
BASE_IMAGE=${BASE_NAME}:${BASE_TAG}
FULL_NAME=linc-full
FULL_TAG=$(git log -n 1 --pretty=format:%H)
FULL_IMAGE=${FULL_NAME}:${FULL_TAG}
LINC_VERSION=$(${SCRIPT_DIR}/get_scm_version.sh)
LINC_NAME=astronrd/linc
LINC_TAG=${LINC_VERSION//[^[:alnum:]_.-]/-}
LINC_IMAGE=${LINC_NAME}:${LINC_TAG}

# Build the base image, using the previously determined git commit hashes for
# the packages we need to build
docker build \
  --build-arg CASACORE_COMMIT=${CASACORE_COMMIT} \
  --build-arg LOFARSTMAN_COMMIT=${LOFARSTMAN_COMMIT} \
  --build-arg IDG_COMMIT=${IDG_COMMIT} \
  --build-arg AOFLAGGER_COMMIT=${AOFLAGGER_COMMIT} \
  --build-arg EVERYBEAM_COMMIT=${EVERYBEAM_COMMIT} \
  --build-arg SAGECAL_COMMIT=${SAGECAL_COMMIT} \
  --build-arg DP3_COMMIT=${DP3_COMMIT} \
  --build-arg WSCLEAN_COMMIT=${WSCLEAN_COMMIT} \
  --build-arg PYTHONCASACORE_COMMIT=${PYTHONCASACORE_COMMIT} \
  --build-arg LINC_VERSION=${LINC_VERSION} \
  --progress plain \
  --file ${SCRIPT_DIR}/Dockerfile-base \
  --tag ${BASE_IMAGE} \
  ${REPO_ROOT}

# Build the full image, taking the base image as starting point
docker build \
  --build-arg BASE_IMAGE=${BASE_IMAGE} \
  --build-arg LINC_VERSION=${LINC_VERSION} \
  --progress plain \
  --file ${SCRIPT_DIR}/Dockerfile-linc \
  --tag ${FULL_IMAGE} \
  ${REPO_ROOT}

# Tag the full image with LINC version number
docker tag \
  ${FULL_IMAGE} \
  ${LINC_IMAGE}

# Tag the full image as latest
docker tag \
  ${FULL_IMAGE} \
  latest
