#!/bin/bash

# identify the parent directory in order to name the service.
PARENT_DIR="${PWD##*/}"
# replace restricted characters.
PARENT_DIR=$( echo $PARENT_DIR | tr ' '. _ )
# retrieve any stack matching the parent dir.
RUNNING_STACK=$( docker stack ls | grep $PARENT_DIR )

# attempt to find a running stack with the specified name.
if [ -z "$RUNNING_STACK" ]; then
  echo "No running stacks were found matching '$PARENT_DIR'.";
  exit 1;
fi
# sanitize the running stack string.
RUNNING_STACK=$( echo $PARENT_DIR | cut -d " " -f1 )

# if we found a running stack, bring it down.
echo "Removing stack $RUNNING_STACK..."
docker stack rm $RUNNING_STACK
WAIT=30
for i in `seq $WAIT -1 1` ; do echo -ne "\rWaiting $i seconds for services to terminate..." ; sleep 1 ; done