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

include pretty

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

export DATA_DIR=$SERVICE_DATASTORE$DB_DATADIR


is_db_locked() {
    local host_db_volume
    if [ "${HOST_DATASTORE+x}" ]; then
        host_db_volume="$HOST_DATASTORE/${SERVICE_NAME}$DB_DATADIR"
    else
        host_db_volume="$DATASTORE/${SERVICE_NAME}$DB_DATADIR"
    fi

    is_volume_used "$host_db_volume"
}


_set_server_db_params() {
    local host_config_volume
    if [ "${HOST_DATASTORE+x}" ]; then
        host_config_volume="$HOST_CONFIGSTORE/${SERVICE_NAME}"
    else
        host_config_volume="$CONFIGSTORE/${SERVICE_NAME}"
    fi

    server_docker_opts+=("-v" "${host_config_volume}/etc/mongod.conf:/etc/mongod.conf"
                         "--add-host" "${SERVICE_NAME}:127.0.0.1")
}

_set_db_params() {
    local docker_ip="$1" docker_network="$2"
    ## XXXvlab: include this in compose-core
    if [ "${_db_params}" != "$docker_ip:$docker_network" ]; then
        db_docker_opts+=("--network" "$docker_network")

        db_cmd_opts+=("--host" "$docker_ip")
        check_command="db.serverStatus().ok"
        _db_params="$docker_ip:$docker_network"
        echo callers: "${FUNCNAME[@]}" >&2
    fi
}


ddb() { dcmd mongo --quiet "$@"; }


djson() {
    local out err
    if ! out=$(ddb); then
        err "Mongo call failed"
        return 128
    fi
    if [ -z "$out" ]; then
        err "Mongo replied with empty output"
        return 64
    fi
    if [ "$(e "$out" | jq -r .ok)" != "1" ]; then
        if ! e "$out" | jq . >/dev/null 2>&1; then
            err "Mongo didn't output JSON, output follows:"
            e "$out" | prefix " | "
            return 32
        fi >&2
        errmsg=$(e "$out" | jq -r '.errmsg')
        code_name=$(e "$out" | jq -r '.codeName')
        err "Mongo failed with error message: $errmsg (code: ${code_name})"
        e "$out"
        return 32
    fi
    e "$out"
    return 0
}

mongo:db:ls() {
    local out
    if out=$(djson < <(echo "JSON.stringify(db.adminCommand( { listDatabases: 1 } ))")); then
        e "$out" | jq -r '.databases[] | .name'
        return 0
    else
        if [ "$(e "$out" | jq -r '.codeName')" == "NotMasterNoSlaveOk" ]; then
            ## equivalent to having no databases
            return 0
        fi
        err "Could not query list of databases."
        return 1
    fi
}


mongo:db:rename() {
    local src="$1" dst="$2" out
    if ! out=$(ddb <<EOF
db.copyDatabase("$src","$dst");
use $src;
db.dropDatabase();
EOF
); then
        err "Could not rename database '$src' to '$dst'."
        err "$out"
        return 1
    fi
    debug "$out"
}


mongo:db:version() {
    local out
    if out=$(ddb < <(echo "db.version()")); then
        e "$out"
        return 0
    else
        err "Could not query version of database."
        return 1
    fi
}