#!/bin/sh
#
# NAME
#    bootstrap -- initialize/update docker environment
#
# SYNOPSIS
#    bootstrap
#    bootstrap shellinit
#
# DESCRIPTION
#    Execute this script without parameters to build the local docker
#    environment.  Once bootstrapped, dependent services are running
#    via docker-compose and the environment variables are written to
#    *build/test-environment* for future use.
#
#    Running this script with the _shellinit_ command line parameter
#    causes it to simply interrogate the running docker environment,
#    update *build/test-environment*, and print the environment to
#    the standard output stream in a shell executable manner.  This
#    makes the following pattern for setting environment variables
#    in the current shell work.
#
#        prompt% $(./bootstrap shellinit)
#
# vim: set ts=2 sts=2 sw=2 et:
PROJECT=sprockets

if test -e /var/run/docker.sock
then
  DOCKER_IP=127.0.0.1
else
  docker-machine status ${PROJECT} >/dev/null 2>/dev/null
  RESULT=$?
  if [ ${RESULT} -ne 0 ]
  then
    docker-machine create --driver virtualbox ${PROJECT}
  fi
  eval $(docker-machine env ${PROJECT} 2>/dev/null) || {
    echo "Failed to initialize docker environment"
    exit 2
  }
  DOCKER_IP=$(docker-machine ip ${PROJECT})
fi

COMPOSE_ARGS=
if test -n "${DOCKER_COMPOSE_PREFIX}"
then
  COMPOSE_ARGS="-p ${DOCKER_COMPOSE_PREFIX}"
fi

get_exposed_port() {
  docker-compose ${COMPOSE_ARGS} port $1 $2 | cut -d: -f2
}

build_env_file() {
  DYNAMODB_PORT=$(get_exposed_port dynamodb 7777)
  (echo "export DOCKER_COMPOSE_PREFIX=${DOCKER_COMPOSE_PREFIX}"
   echo "export DOCKER_TLS_VERIFY=${DOCKER_TLS_VERIFY}"
   echo "export DOCKER_HOST=${DOCKER_HOST}"
   echo "export DOCKER_CERT_PATH=${DOCKER_CERT_PATH}"
   echo "export DOCKER_MACHINE_NAME=${DOCKER_MACHINE_NAME}"
   echo "export DYNAMODB_ENDPOINT=http://${DOCKER_IP}:${DYNAMODB_PORT}"
  ) > $1
}

set -e

mkdir -p build

if test "$1" = 'shellinit'
then
  # just build the environment file from docker containers
  build_env_file build/test-environment
else
  docker-compose ${COMPOSE_ARGS} stop
  docker-compose ${COMPOSE_ARGS} rm --force
  docker-compose ${COMPOSE_ARGS} up -d
  build_env_file build/test-environment
fi
cat build/test-environment