# -*- mode: shell-script -*-

include pretty

export DB_NAME="$SERVICE_NAME"    ## general type of database (ie: postgres/mysql...)
export DB_DATADIR=/var/lib/mysql

export DATA_DIR=$SERVICE_DATASTORE$DB_DATADIR

export LOCAL_DB_PASSFILE="$DATA_DIR/my.cnf"
export CLIENT_DB_PASSFILE=/root/.my.cnf


is_db_locked() {
    local host_db_volume
    if [ "${HOST_DATASTORE+x}" ]; then
        host_db_volume="$HOST_DATASTORE/${SERVICE_NAME}"
    else
        host_db_volume="$DATASTORE/${SERVICE_NAME}"
    fi
    ## ``are_files_locked_in_dir`` doesn't work with mysql here as
    ## tested
    is_volume_used "$host_db_volume"
}


_set_db_params() {
    local docker_ip="$1" docker_network="$2"

    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

    [ -f "$CLIENT_DB_PASSFILE" ] || touch "$CLIENT_DB_PASSFILE"

    server_docker_opts+=()
    db_docker_opts+=("--network" "$docker_network")
    db_cmd_opts+=("-h" "$docker_ip")
    check_command="SELECT 1;"
}

_set_server_db_params() {
    server_docker_opts+=()
}


ddb () { dcmd mysql "$@"; }


##
## Entrypoints
##


db_create () {
    local dbname="$1"
    ## Using this instead of pipes is important so that trap works
    debug "Create if not exists '$dbname' database..."
    ddb < <(echo "CREATE DATABASE IF NOT EXISTS \`$dbname\`")
}

db_grant_rights () {
    local dbname="$1" user="$2" password="$3"
    ## Using this instead of pipes is important so that trap works
    debug "Grant all on $dbname to $user"
    ddb < <(echo "GRANT ALL ON \`$dbname\`.* TO '$user'@'%' IDENTIFIED BY '$password'")
}

check_access() {
    local dbname="$1" user="$2" password="$3"
    ## Using this instead of pipes is important so that trap works
    debug "Check if credentials for user '$user' can access database '$dbname'"
    ddb --user="$user" --password="$password" "$dbname" < <(echo "SELECT 1")
}