#! /bin/bash

IMAGES=(
    docker.idiap.ch/beat/beat.env.system.python:1.1.2
    docker.idiap.ch/beat/beat.env.db.examples:1.1.1
    docker.idiap.ch/beat/beat.env.cxx:1.0.2
    docker.idiap.ch/beat/beat.env.client:1.2.0
)


# Find all the missing images
declare -a MISSING_IMAGES

for IMAGE in ${IMAGES[@]}; do
    IMAGE_HASH=$(docker images -q $IMAGE)

    if [ -z "$IMAGE_HASH" ]; then
        MISSING_IMAGES+=($IMAGE)
    fi
done


# If there are some images missing, ask the user if he wants to download them
if [ ${#MISSING_IMAGES[@]} -gt 0 ]; then
    echo "--------------------------------------------------------------------------------------"
    echo "The following docker images are required (at least for the tests), but were not found:"
    echo
    for IMAGE in ${MISSING_IMAGES[@]}; do
        echo "    - $IMAGE"
    done
    echo

    MUST_PULL=0

    if [ -z "$CI_SERVER" ]; then
        read -p "Do you want to install them now? (yes/no) " -n 1 -r
        echo

        if [[ $REPLY =~ ^[Yy]$ ]]; then
            MUST_PULL=1
        fi
    else
        MUST_PULL=1
    fi

    if [ $MUST_PULL -eq 1 ]; then
        # Log in the registry if needed
        if [ -z "$CI_SERVER" ]; then
            if ! grep -q "docker.idiap.ch" ~/.docker/config.json ; then
                docker login docker.idiap.ch
            fi
        else
            docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN docker.idiap.ch
        fi

        # Pull the images
        for IMAGE in ${MISSING_IMAGES[@]}; do
            echo
            CMD="docker pull $IMAGE"
            echo "> $CMD"
            $CMD
        done
    fi
fi
