<?php

// Common settings
$wpdb->persistent = true;
$wpdb->max_connections = 30;

define("NOBLOGS_BACKEND_CONFIG", "/etc/noblogs/backends");
define("NOBLOGS_MASTER_CONFIG", "/etc/noblogs/master");

include_once('r2db/db-hash.php');
include_once('r2db/db-backends.php');

// Add the global database (configured in wp-config.php), stores the global
// blogs and users tables.
$is_master = __gf_ai_is_master();

$wpdb->add_database(array(
    "host" => DB_HOST,
    "user" => DB_USER,
    "password" => DB_PASSWORD,
    "name" => DB_NAME,
    "dataset" => "global",
    "write" => $is_master, "read" => 1, "timeout" => 2
    ));

// This is the write-only master.
if (!$is_master) {
    $wpdb->add_database(noblogs_load_master(NOBLOGS_MASTER_CONFIG));   
}


// Add all the sharded blog databases.
$wpdb_reverse_backend_map = noblogs_load_backends(NOBLOGS_BACKEND_CONFIG, $wpdb->hash_map);

// Ai patch: allows to understand if the current database is the master server
function __gf_ai_is_master() {
    $master_dsn = trim(file_get_contents('/etc/noblogs/master'));
    preg_match('/@172.16.1.(\d+):/', $master_dsn, $m);
    $master_id = $m[1];
    if (!empty($_SERVER['SERVER_ADDR']))  
        return (int) ('172.16.1.'.$master_id == $_SERVER['SERVER_ADDR']);//works on web
    return (int) ($master_id == $_SERVER['SERVER_PUBLIC_ID']);//works on cli
}