#!/bin/bash

# CONTAINER_REGISTRY="harbor.vimpelcom.ru"
# PRODUCT="vega/stage"
# PRODUCT_VERSION="0.5.3"

if [[ $# -eq 0 ]] ; then
    echo "No arguments supplied"
    exit 1
fi

if [[ -z "$1" ]] ; then
    echo "No argument CONTAINER_NAME"
    exit 1
fi

GREEN=$'\033[0;32m'
RED=$'\033[0;31m' 
BLUE=$'\033[0;36m' 
WHITE=$'\033[0;37m' 
RESET=$'\033[0m'

CONTAINER_NAME=${1}
IMAGE_URL="$CONTAINER_REGISTRY/$PRODUCT/$IMAGE_NAME:$PRODUCT_VERSION"
DOCKER_COMPOSE_EXEC="docker-compose"

echo -e "${GREEN}IMAGE_URL${RESET}: ${IMAGE_URL}"

if ! [ -x "$(command -v docker-compose)" ]; then
    DOCKER_COMPOSE_EXEC="docker compose"
fi

# для -z необходимо указывать параметры в двойных ковычках
if [ -z "$(docker ps -aq -f name=^${CONTAINER_NAME}$)" ]; then
  echo -e "${RED}${CONTAINER_NAME:-container} not running.${RESET}"
  exit 1
fi

COMPOSE_FILE="$(docker inspect --format '{{index .Config.Labels "com.docker.compose.project.config_files"}}' $CONTAINER_NAME | tr , \\n | xargs grep -wH $IMAGE_NAME | cut -d: -sf1 | uniq)"
COMPOSE_ALL_FILES="-f $COMPOSE_FILE"

cp $COMPOSE_FILE "$COMPOSE_FILE.orig"
# sed -i '/image: .*'$IMAGE_NAME'/ s|:.*|: '"$IMAGE_URL"'|' $COMPOSE_FILE
sed -r -i '/image: .*'$IMAGE_NAME'(:|@|$)/ s|:.*|: '"$IMAGE_URL"'|' $COMPOSE_FILE

if [ -e ~dorootless/docker-compose-svc.yaml ]; then
COMPOSE_SVC_FILE=~dorootless/docker-compose-svc.yaml
COMPOSE_ALL_FILES="-f $COMPOSE_SVC_FILE -f $COMPOSE_FILE"
fi

$DOCKER_COMPOSE_EXEC $COMPOSE_ALL_FILES pull $CONTAINER_NAME
$DOCKER_COMPOSE_EXEC $COMPOSE_ALL_FILES up -d

if [ "$(docker ps -a -q -f name=ingress)" ]; then
  $DOCKER_COMPOSE_EXEC $COMPOSE_ALL_FILES exec ingress angie -s reload
fi
