#!/bin/sh

set +x

if [ -n "$CI" ]; then
    echo "  Prevent executing script on CI environment"
    exit 0
fi

if [ "$1" == "" ]; then
	echo "  Usage: dep-stack <stack-name>"
	echo
	echo "  Flags:"
	echo "    -a - deploy all available stacks in the directory"
	exit 1
fi

if [ "$(command -v jq)" == "" ]; then
    echo "  jq not found, please install jq (https://stedolan.github.io/jq/download/) to your workstation"
    exit 1
fi

if [ "$DOCKER_HOST" == "" ]; then
	echo "  DOCKER_HOST env variable was not specified, using 'localhost' instead"
fi

if [ "$DOCKER_DIR" == "" ]; then
	echo "  DOCKER_DIR env variable was not specified, using 'dev' instead"
	export DOCKER_DIR=dev
fi

export HOST_IP=$(ifconfig | grep -E "([0-9]{1,3}\\.){3}[0-9]{1,3}" | grep -v 127.0.0.1 | awk '{ print $2 }' | cut -f2 -d: | head -n1)

function check_network {
    local network_name='global'
    local network_id=$(docker network ls -q -f "name=$network_name")

    if [ "$network_id" == "" ]; then
        echo "  $network_name network does not exists, use the command below to create network:"
        echo ""
        echo "  $ docker network create -d overlay --attachable $network_name"
        exit 1
    fi
}

function check_swarm_state {
    local node_state="$(docker info -f '{{ json .}}' | jq -r .Swarm.LocalNodeState)"
    if [ "$node_state" == "inactive" ]; then
        echo "  Docker Swarm should be configured, use the command below to configure Docker Swarm mode:"
        echo ""
        echo "  $ docker swarm init"
        echo ""
        exit 1
    fi
}

function dep_stack {
    if [ "$DOCKER_HOST" != "" ]; then
        echo "  Deploying stack --with-registry-auth..."
        docker stack deploy -c ${DOCKER_DIR}/docker-compose.$1.yml $1 --with-registry-auth
        exit 0
    fi
	docker stack deploy -c ${DOCKER_DIR}/docker-compose.$1.yml $1
}

if [ "$1" == "-a" ]; then
    for file in ${DOCKER_DIR}/*.yml; do
        filename=$(basename "$file")
        service_name=$(echo ${filename} | cut -d '.' -f2)
        dep_stack ${service_name}
    done
    exit 0
fi

check_swarm_state
check_network

dep_stack $1
