#!/usr/bin/env bash
source .env

printf "\n----\n\t** $CO_VERSION\n\n";

PARAMETERS="$@"

function_helper_question() {
    if [ "$PARAMETERS" == "--force" ] || [ "$PARAMETERS" == "-f" ]
    then
        echo "Force argument detected."
        REPLY='Y'
    else
        read -p "$1" -n 1 -r
        echo
    fi
}

function_helper_question "Build images?"
if [[ $REPLY =~ ^[Yy]$ ]]
then
    #Delete namespace local images
    docker images | grep -v "REPOSITORY\|none\|${CO_VERSION}" | grep container-orchestration | awk '{printf $1; printf ":"; print $2}' | xargs -L1 docker rmi -f

    declare -a serviceList=(\
      php-fpm \
      php-supervisor \
      php-dev \
      nginx-core \
      nginx-upstream \
    )
    for serviceName in "${serviceList[@]}"
    do
        printf "\n>> Build
        * image: ${serviceName}
        * current tag: ${CO_VERSION}
        * vcs ref: ${VCS_REF}
        * build date: ${BUILD_DATE}
        * manual command: docker-compose -f docker-compose-php.yml -f docker-compose-nginx.yml build ${serviceName};
        \n";

        docker-compose -f docker-compose-php.yml -f docker-compose-nginx.yml --log-level INFO build ${serviceName};

        if [ $? -eq 0 ]; then
            printf ">> Successfully builded image [${serviceName}] ${CO_VERSION}\n";
            docker tag gpupo/container-orchestration:${serviceName}-${CO_VERSION} gpupo/container-orchestration:${serviceName}
        else
            printf ">> ERROR: FAILED with image [${serviceName}] ${CO_VERSION}\n";
            exit 1;
        fi
    done;
fi

tagImages() {
    COL_SPACE=" | "
    printf "FULLNAME $COL_SPACE SIMPLE-NAME $COL_SPACE LATEST-NAME\n"

    docker images | grep $CO_VERSION | cut -d $' ' -f 24 | while read FULLNAME
    do
        SIMPLE="${FULLNAME/-$CO_VERSION/}"
        printf "$FULLNAME $COL_SPACE $SIMPLE $COL_SPACE $LATEST\n";
        # docker tag gpupo/container-orchestration:$FULLNAME gpupo/container-orchestration:$SIMPLE
    done
}

# function_helper_question "Tag images? "
# if [[ $REPLY =~ ^[Yy]$ ]]
# then
#     tagImages | column -t
# fi

function_helper_question "Publish images to Docker Hub? "
if [[ $REPLY =~ ^[Yy]$ ]]
then
    printf ">> Current Tags:\n";
    docker image ls | grep container-orchestration;
    printf ">> Pushing Tags..\n";
    docker push gpupo/container-orchestration --all-tags
fi
