#!/bin/sh
# RUN IN REPO ROOT DIR !!

export IMAGE_PREFIX="git.pbiernat.dev/egommerce/identity"
export BUILDER_IMAGE="egommerce-builder:identity"
export BUILD_TIME=$(date +"%Y%m%d%H%M%S")
export SERVER_IMAGE="$IMAGE_PREFIX-svc"
# export WORKER_IMAGE="$IMAGE_PREFIX-worker"
export DOCKER_BUILDKIT=1

TARGET=${1:-latest}

[ ! -d "src/vendor" ] && sh -c "cd src; go mod vendor"

echo "Building tmp $IMAGE_PREFIX image..."
docker build --rm -t $BUILDER_IMAGE -f Dockerfile.builder .

if [ $TARGET = "latest" ]
then
    # SERVER
    docker build --build-arg SVC_NAME=identity-svc --build-arg SVC_VER="1.0" --build-arg BIN_OUTPUT=/go/bin/server \
        --build-arg BUILDER_IMAGE=$BUILDER_IMAGE --build-arg BUILD_TIME --rm --cache-from $SERVER_IMAGE:$TARGET -t $SERVER_IMAGE:$TARGET \
        -f Dockerfile.target . >/dev/null 2>&1 && echo "Successfully tagged $SERVER_IMAGE:$TARGET"
    # docker tag $SERVER_IMAGE:$TARGET $SERVER_IMAGE:$TARGET
    
    # WORKER
    # docker build --build-arg SVC_NAME=identity-worker --build-arg SVC_VER="1.0" --build-arg BIN_OUTPUT=/go/bin/worker \
    #     --build-arg BUILDER_IMAGE=$BUILDER_IMAGE --build-arg BUILD_TIME --rm --cache-from $WORKER_IMAGE:$TARGET -t $WORKER_IMAGE:$TARGET \
    #     -f Dockerfile.target . >/dev/null 2>&1 && echo "Successfully tagged $WORKER_IMAGE:$TARGET"
else
    # SERVER
    docker build --build-arg SVC_NAME=identity-svc --build-arg SVC_VER="dev" --build-arg BIN_OUTPUT=/go/bin/server \
        --build-arg BUILDER_IMAGE=$BUILDER_IMAGE --build-arg BUILD_TIME --rm --no-cache -t $SERVER_IMAGE:$TARGET \
        -f Dockerfile.target . && echo "Successfully tagged $SERVER_IMAGE:$TARGET"
    # docker tag $SERVER_IMAGE:$TARGET $SERVER_IMAGE:$TARGET

    # WORKER
    # docker build --build-arg SVC_NAME=identity-worker --build-arg SVC_VER="dev" --build-arg BIN_OUTPUT=/go/bin/worker \
    #     --build-arg BUILDER_IMAGE=$BUILDER_IMAGE --build-arg BUILD_TIME --rm --no-cache -t "$WORKER_IMAGE:$TARGET" \
    #     -f Dockerfile.target . >/dev/null 2>&1 && echo "Successfully tagged $WORKER_IMAGE:$TARGET"
fi

echo "Done."
