#!/usr/bin/env bash

set -e

mysql --user @MYSQL_ADMIN@ --password=@MYSQL_ADMIN_PASSWD@ --batch -e "DROP DATABASE @TANGO_DB_NAME@;" || true
mysql --user @MYSQL_ADMIN@ --password=@MYSQL_ADMIN_PASSWD@ --batch -e "source create_db.sql;"

rm -f tdb_output.log

(
  # Heavily inspired by https://gitlab.com/tango-controls/cppTango/-/blob/main/cpp_test_suite/environment/start_server.sh.cmake
  export MYSQL_USER=@MYSQL_ADMIN@
  export MYSQL_PASSWORD=@MYSQL_ADMIN_PASSWD@

  server_pid="$(sh -c 'printf $PPID')"
  echo $server_pid > tdb.pid

  exec 1<&-
  exec 2<&-
  exec 1<> tdb_output.log
  exec 2>&1
  exec ./Databaseds 2 -v5 -ORBendPoint giop:tcp:127.0.0.1:10000
) &
echo $! > tdb.pid
