#!/bin/bash
set -eo pipefail

# Password protect webui
echo Creating webui user
echo $WEBUI_PASSWORD | htpasswd -ci /var/www/html/.htpasswd webui

# Checking for DB liveness before continuing with DB set up.
count=0
while [ $count -lt 4 ]; do
  if [[ $(mysql -h$CLUEBRINGER_DB_HOST -uroot -p$MYSQL_ROOT_PASSWORD -e "select 1" &>/dev/null ; echo $?) -ne 0 ]]; then
    echo "Waiting for DB to be ready."
    sleep 15
    let count+=1
  else
    echo "DB appears to be ready."
    break
  fi
done
# Die if DB doesn't come up in time.
if [ $count -eq 4 ]; then
  echo "!!!WARNING!!! DB didn't come up in time."
  exit 0
fi

# Set up DB if it's empty.
if [[ $(mysql -N -h$CLUEBRINGER_DB_HOST -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '$MYSQL_DATABASE';") == 0 ]]; then
  echo "Setting up cluebringer DB."

  # Set up DB and User
  if [[ $(mysql -N -h$CLUEBRINGER_DB_HOST -uroot -p$MYSQL_ROOT_PASSWORD -e "create database $MYSQL_DATABASE;use $MYSQL_DATABASE;CREATE USER '$MYSQL_USER'@'%' IDENTIFIED BY '$MYSQL_PASSWORD';GRANT ALL PRIVILEGES ON $MYSQL_DATABASE.* TO '$MYSQL_USER'@'%';") -ne 0 ]]; then
    echo "Can't create DB and Policyd DB user!"
    exit 0
  fi

  # Add our policys from sql if they exist.
  if [[ -e /tmpl/cluebringer/import/policy.sql ]]; then
    echo "Importing our configuration."
    mysql -h$CLUEBRINGER_DB_HOST -u$MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE < /tmpl/cluebringer/import/policy.sql
    echo "Done."
  else
    echo "Additional sql configuration no found importing standart configuration."
    mysql -h$CLUEBRINGER_DB_HOST -u$MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE < /tmp/policyd-db.mysql
  fi
else
  echo "Cluebringer DB not empty, exiting."
  exit 0
fi
