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

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

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_staging.txt"
cd-docker-compose "$CD_TO" pull
PULL_OK=$?
if [[ $PULL_OK -eq 0 && "$1" == "-d" ]]; then
    echo "Copia del database da produzione a staging..."
    if ./copydb.sh --from production --to staging;  #l'utente può dire no
    then
        echo "Copia completata"
    else
        echo "Copia annullata"
    fi
fi
[[ $PULL_OK -eq 0 ]] && cd-docker-compose "$CD_TO" up -d
echo "Master caricato su ambiente di TEST (Staging)"
log_images "dopo" "log_deployment_staging.txt"
