//will be put in your project by Bluemix once you add the Cloudant database to your Bluemix
//application.
// vcap_services Extraction
$services_json = json_decode(getenv('VCAP_SERVICES'), true);
$VcapSvs = $services_json["cloudantNoSQLDB"][0]["credentials"];
//Debug: If you want to see all the variables returned you can use this line of code.
//var_dump($services_json);
// Extract the VCAP_SERVICES variables for Cloudant connection.
$myUsername = $VcapSvs["username"];
$myPassword = $VcapSvs["password"];
try {
    // Let's login to the database.
    $sag = new Sag($myUsername . ".cloudant.com");
    $sag->login($myUsername, $myPassword);
    // Now that we are logged in, we can create a database to use
    $sag->createDatabase("mydatabase");
    $sag->setDatabase("mydatabase");
    if (!$sag->put("myId", '{"myKey":"Hello World from Cloudant!"}')->body->ok) {
        error_log('Unable to post a document to Cloudant.');
    } else {
        // We are now going to read a document from our cloudant database. We are going
        // to retrieve the value associated with myKey from the body of the document.
        //The SAG PHP library takes care of all the gory details and only retrieves the value.
        $resp = $sag->get('myId')->body->myKey;
        echo $resp;
    }
    // Assuming everything above was executed without error, we now are connected to the
    // database and have retrieved the value.
    //NOTE: Since we have a connection to the database, we can query the database for other
    //      documents and retrieve other variables at a later time. We do not need to connect
    //      to the database again.
*/
$fileStorageDir = getConfig($config, 'file_storage_dir', TRUE);
$cachePath = getConfig($config, 'cache_dir', TRUE);
/* each user has their own data directory, easy to link files
   to users in case the index breaks, so at least the files 
   themselves are not lost, only the metadata added by the user and
   sharing groups.
 */
$dbName = getConfig($config, 'db_name', TRUE);
$s = new Sag();
$dbs = $s->getAllDatabases()->body;
/* if db already exists, delete it */
if (in_array($dbName, $dbs)) {
    $s->deleteDatabase($dbName);
}
$s->createDatabase($dbName);
$s->setDatabase($dbName);
/* load all the map/reduce js functions from mapReduce directory */
$views = array();
foreach (glob("docs/mapReduce/*") as $mrFiles) {
    list($name, $type) = explode(".", basename($mrFiles));
    $views[$name][$type] = file_get_contents($mrFiles);
}
$view = array("_id" => "_design/files", "type" => "view", "language" => "javascript", "views" => $views);
// Add the view
$s->post($view);
// Delete all cache entries as to not accumulate too many
foreach (glob($cachePath . "/*") as $cacheEntry) {
    unlink($cacheEntry);
}
// Import all new entries