#! /bin/bash --
set -e
set -o pipefail

DOCKER_NAMESPACE="briq"
PROJ="sangue"
cd "$(dirname "$0")" || exit 1
CD_TO="./production/"

cd-docker-compose() {
    (cd "$1" && docker-compose "${@:2}")
}

log_images() {
    if cd-docker-compose "$CD_TO" exec "$PROJ" bash -c 'exit 0'; then
        {
            date | tr -d '\n';
            echo -ne "\t";
            cd-docker-compose "$CD_TO" exec "$PROJ" bash -c 'cat /git_info' | jq -r '.lhash' | tr -d '\n';
            echo -ne '\t';
            cd-docker-compose "$CD_TO" images -q "$PROJ" | tr -d '\n';
            echo -e "\t$1";
        } >> "$2"
    else
        {
            date | tr -d '\n';
            echo -ne "\timpossibile leggere il tag git\t";
            { cd-docker-compose "$CD_TO" images -q "$PROJ" || echo "N/A"; } | tr -d '\n';
            echo -e "\t$1";
        } >> "$2"
    fi
}
log_images "prima" "log_deployment_production.txt"

docker tag "$PROJ":production "$PROJ":backup || true
docker tag docker.briq.it/"$DOCKER_NAMESPACE/$PROJ":master "$PROJ":production
cd-docker-compose "$CD_TO" up -dt1
log_images "dopo" "log_deployment_production.txt"
