#!/bin/bash

if ! [ -x "$(command -v jq)" ]; then
  echo "Please install 'jq' - brew install jq, apt install jq..."
  exit 1
fi
if ! [ -f "package.json" ]; then
  echo "This script needs to be run from the root of the repository"
  exit 1
fi
if ! [ -f "secrets/sqlsidecar_selfsigned.key" ]; then
  echo "Development key/cert missing. Generating now..."
  ./bin/generate_self_signed_cert.sh
fi

export NODE_ENV=development

yarn

COMPOSE_CMD="docker-compose up -d --remove-orphans"
${COMPOSE_CMD} mysql mysql_slave statsd 2>&1 | tee .devlog.plain

. ./bin/find_compose_services.sh

if fgrep "Creating " .devlog.plain | fgrep "mysql" > /dev/null; then
  MYSQL_USER=$(fgrep MYSQL_USER docker-compose.yml | awk '{print $2}' | head -n1)
  MYSQL_PASS=$(fgrep MYSQL_PASSWORD docker-compose.yml | awk '{print $2}' | head -n1)
  MYSQL_SETUP="./bin/mysql_setup.sh ${DOCKER_SRV}:${MYSQL_PORT} ${DOCKER_SRV}:${MYSQL_SLAVE_PORT} ${MYSQL_PASS}"
  echo "Running Mysql Setup: \"${MYSQL_SETUP}\""
  $MYSQL_SETUP
fi

mkdir -p _db

set -x

AGENT_DB_HOST="${DOCKER_SRV}" \
AGENT_DB_PORT="${MYSQL_PORT}" \
DEV_SECONDARY_AGENT_DB_HOST="${DOCKER_SRV}" \
DEV_SECONDARY_AGENT_DB_PORT="${MYSQL_SLAVE_PORT}" \
API_DB_TYPE="mysql" \
API_DB_HOST="${DOCKER_SRV}" \
API_DB_PORT="${MYSQL_PORT}" \
STATSD_URIS="${DOCKER_SRV}:${STATSD_PORT}" \
API_REJECT_UNAUTHORIZED="false" \
REGISTRATION_SECRET="Aregistrationsecret_just_for_development" \
AGENT_NAME="dev_mysql" \
BLUEBIRD_WARNINGS=0 \
./node_modules/.bin/gulp watch
