#!/bin/sh

set -e

if [[ "${USE_CONSUL}" == "false" ]];
then
  npm start
else
  : "${CONSUL_IP:=172.17.0.1}"
  : "${CONSUL_PORT:=8500}"

  rm -rf "config/database.json" && consul-template \
    -consul-addr="${CONSUL_IP}:${CONSUL_PORT}" \
    -exec="$(npm bin)/db-migrate up --config config/database.json" \
    -template="config/database.json.ctmpl:config/database.json"

  rm -rf "config/application.json" && consul-template \
    -consul-addr="${CONSUL_IP}:${CONSUL_PORT}" \
    -exec="node ." \
    -exec-reload-signal=SIGHUP \
    -template="config/application.json.ctmpl:config/application.json"
fi
