<?php
  $page_title = "Allmydata - Deep Size";

  require(".inc/includes.php");
  require(".inc/ui/dbconnection.php");

  // get the batch_id for this run
  $query = "select max(batch_id) from user_space_usage where true";
  $q_results = mysql_query($query);
  if($q_results) {
    $results = mysql_fetch_row($q_results);
    $batch_id = $results[0];
    $batch_id = $batch_id + 1;
  } else {
    $batch_id = 0;
  }

  // get list of accounts and then figure out amount of space used
  $query = "select * from user where base_uri <> '' and active = 1 order by account_id desc";
  $q_results = mysql_query($query);
  $i = 1;
  while($results = mysql_fetch_array($q_results)) {
    $base_uri = $results['base_uri'];
    $account_id = $results['account_id'];
    $email = $results['email'];
    $ch = curl_init();
    $uri_url = "http://prodtahoe5.allmydata.com:8123/uri/";
    $full_url = $uri_url . urlencode($base_uri) . "?t=deep-stats";
    curl_setopt($ch, CURLOPT_URL, $full_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $stats_data_raw = curl_exec($ch);
    $stats_data = json_decode($stats_data_raw);
    $size = floatval($stats_data->{'size-immutable-files'})/(1000*1000);
    $inner_query = "update user set used_quota=" . $size . " where account_id = ". $account_id;
    $results = mysql_query($inner_query);
    $inner_query = "insert into user_space_usage (account_id, batch_id, mb_used) values ({$account_id}, {$batch_id}, {$size})";
    echo $account_id . " " . $size . " " . $batch_id . "\n";
    $results = mysql_query($inner_query);
    $i = $i + 1;
  }
?>