#!/bin/bash

## Init is run on host
## For now it is run every time the script is launched, but
## it should be launched only once after build.

## Accessible variables are:
## - SERVICE_NAME        Name of current service
## - DOCKER_BASE_IMAGE   Base image from which this service might be built if any
## - SERVICE_DATASTORE           Location on host of the DATASTORE of this service
## - SERVICE_CONFIGSTORE         Location on host of the CONFIGSTORE of this service


. lib/common

set -e

if [ "${HOST_DATASTORE+x}" ]; then
    export HOST_DB_PASSFILE="$HOST_DATASTORE/${SERVICE_NAME}$DB_DATADIR/my.cnf"
else
    export HOST_DB_PASSFILE="$CLIENT_DB_PASSFILE"
fi


if ! [ -d "$HOST_DATASTORE/${SERVICE_NAME}$DB_DATADIR" ]; then

    MYSQL_ROOT_PASSWORD="$(gen_password)"
    mkdir -p "${HOST_DB_PASSFILE%/*}"
    ## XXXvlab: this won't help support multiple project running on the
    ## same host
    cat <<EOF > "$HOST_DB_PASSFILE"
[client]
password=$MYSQL_ROOT_PASSWORD
EOF
    chmod 600 "$HOST_DB_PASSFILE"

    ## deactivating final connection check
    ddb () { true; }
    export -f ddb
    ensure_db_docker_running || exit 1

    docker exec -i "$_DB_NAME" mysql <<EOF
USE mysql;
GRANT ALL ON *.* TO 'root'@'%' IDENTIFIED BY '$MYSQL_ROOT_PASSWORD' WITH GRANT OPTION;
GRANT ALL ON *.* TO 'root'@'localhost' IDENTIFIED BY '$MYSQL_ROOT_PASSWORD' WITH GRANT OPTION;
SET PASSWORD FOR 'root'@'localhost'=PASSWORD('${MYSQL_ROOT_PASSWORD}');
FLUSH PRIVILEGES;
EOF

    . lib/common

    err=$(echo "$check_command" | ddb 2>&1 >/dev/null) || {
        err "Docker run probably failed to do it's job."
        echo "$err" | prefix "  " >&2
        exit 1
    }

    info "New root password for mysql. "
fi