#!/bin/bash

set -e

if [[ -n $1 ]]; then
  DEPLOY_ENV=$1
fi

if [[ -z $SERVICE ]]; then
  SERVICE=${PWD##*/}
fi

if hash buildkite-agent 2>/dev/null ; then
  echo '--- retrieving service file'
  buildkite-agent artifact download ${SERVICE}@.service .
fi

if [[ ! -e ${SERVICE}@.service ]]; then
  echo "${SERVICE}@.service file is missing. Run script/build to create it."
  exit 1
fi

fleetctl destroy ${SERVICE}@.service || true # may not exist
fleetctl submit ${SERVICE}@.service

echo '--- (re-)starting fleet service instances'
for i in {1..3}; do
  fleetctl stop ${SERVICE}@$i
  fleetctl destroy ${SERVICE}@$i || true # may not exist
  fleetctl start ${SERVICE}@$i
  # TODO: Use consul to see if ${SERVICE}@$i is healthy yet before moving on
  sleep 30
done

if [[ -n ${DEPLOY_ENV} ]]; then
  DOCKER_REPO=$(grep "Environment=DOCKER_REPO=" ${SERVICE}@.service | cut -f 3 -d =)
  IMAGE_TAG=$(grep "Environment=VERSION=" ${SERVICE}@.service | cut -f 3 -d =)
  DOCKER_IMAGE="${DOCKER_REPO}:${IMAGE_TAG}"
  echo "--- tagging and pushing ${DOCKER_REPO}:${DEPLOY_ENV}"
  docker pull ${DOCKER_IMAGE} # in case it isn't on this host yet
  docker tag -f ${DOCKER_IMAGE} ${DOCKER_REPO}:${DEPLOY_ENV}
  docker push ${DOCKER_REPO}:${DEPLOY_ENV}
  if [[ "${DEPLOY_ENV}" = "production" ]]; then
    docker tag -f ${DOCKER_IMAGE} ${DOCKER_REPO}:latest
    docker push ${DOCKER_REPO}:latest
  fi
fi
