#!/usr/bin/env bash
set -euo pipefail

main_branch_name="develop/sim"

# if there is one variable, set local_build to true, this build images from
# local git instead of checking to make sure you are on head of develop/sim
if [ $# -eq 1 ]; then
    local_build=true
else
    local_build=false
fi

if [ "$local_build" != true ]
then
    # Make sure, you are on the main branch
    current_branch=`git rev-parse --abbrev-ref HEAD`
    if [ $current_branch != "${main_branch_name}" ]
    then
        echo "Error:: Not on ${main_branch_name}, branch is $current_branch"
        exit 1
    fi

    # Update the branch
    git pull origin ${main_branch_name}

    # Make sure there are no uncommitted changes
    if [ -n "$(git status -s -uall)" ]
    then
        echo "Error:: You have uncommited changes"
        echo
        git status -uall
        exit 1
    fi
fi

# Build the current Version of this service image locally

service=$(basename $PWD)
if [ $service == "kong" ]; then
    service="restapi"
    # build gitinfo file that can be later copied by Dockerfile
    echo "Generating gitinfo"
    ./gradlew :restapi:clean :restapi:bootJar -Pgitinfo -x test
fi

version_next=$(git rev-parse --short HEAD)

image_tag="marvel2-$service:$version_next"
image_tag_latest="marvel2-$service:latest"

echo "..... Building $image_tag"
current_path=$(pwd)
echo "Current path is $current_path"

# Build Docker image
(
  set -x
  if [ -f "./Dockerfile" ]; then
    docker build ./ --tag "$image_tag" --tag "$image_tag_latest"
  elif [[ $current_path == *"kafka"* ]];then
    # kafka submodule/subproject
    # set PATH to be driving/sim (i.e ../../../../)
    docker build ../../../../ -f ../../kafka.Dockerfile --tag "$image_tag" --tag "$image_tag_latest" --build-arg project=$service
  elif [[ $current_path == *"metrics"* ]]; then
    # metrics submodule/subproject
    ../../gradlew clean build
    docker build ./ -f ../../metrics.Dockerfile --tag "$image_tag" --tag "$image_tag_latest" --build-arg project=$service
  fi
)
