#! /bin/bash

# Usage:
#   cfk-start <service>
#
#   Starts a cfk service container.
#
#   This does monitor the container, so it won't attempt
#   to restart if the container dies. That is upstart's
#   duty (upstart monitoring can be initialized with
#   `start <service>`)

set -o pipefail

CONTAINER=$1

# Make sure that weave services are running

WEAVE_RUNNING=$(docker ps --format "{{ .Names }}" | grep ^weave$ | wc -l)
if [ "$WEAVE_RUNNING" -ne "1" ]; then
  echo "Error: Weave router is not running!"
  exit 1
fi

PROXY_RUNNING=$(docker ps --format "{{ .Names }}" | grep ^weaveproxy$ | wc -l)
if [ "$PROXY_RUNNING" -ne "1" ]; then
  echo "Error: Weave proxy is not running!"
  exit 1
fi

DISCOVERY_RUNNING=$(docker ps --format "{{ .Names }}" | grep ^discovery$ | wc -l)
if [ "$DISCOVERY_RUNNING" -ne "1" ]; then
  echo "Error: Weave discovery is not running!"
  exit 1
fi

# Load cfk environment
eval $(cfk-env)

# Load any service-specific environment
if [ -f /etc/default/$CONTAINER ]; then
  eval $(cat /etc/default/$CONTAINER | sed 's/^/export /')
fi

cd /usr/src/cfk

sleep 10
PRECONDITION=$(cat docker-compose.yml | shyaml get-value $CONTAINER.environment.CFK_START_PRECONDITION | sed 's/\$\$/$/g' || echo "echo No Precondition")
eval "$PRECONDITION" || (echo "Error: $CONTAINER precondition check failed!" && exit 1) || exit 1

# Remove old instance
docker-compose stop $CONTAINER || exit 1
docker-compose rm -f $CONTAINER || exit 1

# Identify machine and hostname
NAME=$(weave status | grep Name)
MACHINE=$(echo $NAME | awk '{ print $2 }' | cut -f 1 -d '(')
HOSTNAME=$(echo $NAME | awk '{ print $2 }' | cut -f 2 -d '(' | cut -f 1 -d ')')

# Start service via docker-compose and give it some time to initialize
docker-compose up -d $CONTAINER || exit 1
sleep 10
