#!/bin/bash
set -e

# Check if we are in the right place
if [ ! -d ./services ]; then
    echo "You must run this command from the project's root folder."
    exit 1
fi

# Set service and caching switch
if [[ "x$1" == "xnocache" ]] ; then
    NOCACHE=true
    SERVICE=""
elif [[ "x$2" == "xnocache" ]] ; then
    NOCACHE=true 
    SERVICE=$1
else
    if [[ "x$NOCACHE" == "x" ]] ; then
        # Set the default only if we did not get any NOCACHE env var
        NOCACHE=false
    fi
    SERVICE=$1
fi

if [[ "x$NOCACHE" == "xtrue" ]] ; then
    BUILD_COMMAND="docker build --no-cache"
else
    BUILD_COMMAND="docker build"
fi

if [[ "x$SERVICE" == "x" ]] ; then
    
    # Build all services
    NOCACHE=$NOCACHE rosetta/build base_ubuntu18.04
    NOCACHE=$NOCACHE rosetta/build base_ubuntu22.04
    NOCACHE=$NOCACHE rosetta/build slurmbase
    NOCACHE=$NOCACHE rosetta/build slurmcluster    
    NOCACHE=$NOCACHE rosetta/build slurmclustermaster    
    NOCACHE=$NOCACHE rosetta/build slurmclusterworker    
    NOCACHE=$NOCACHE rosetta/build standaloneworker     
    NOCACHE=$NOCACHE rosetta/build dregistry
    NOCACHE=$NOCACHE rosetta/build webapp
    NOCACHE=$NOCACHE rosetta/build postgres
    NOCACHE=$NOCACHE rosetta/build proxy
    
else

    # Build a specific image
    echo ""
    if [[ "x$NOCACHE" == "xtrue" ]] ; then
        echo "-> Building $SERVICE (without cache)..."
    else
        echo "-> Building $SERVICE..."
    fi
    echo ""
    $BUILD_COMMAND services/$SERVICE -t rosetta/$SERVICE

fi
