#!/usr/bin/env perl

use warnings;
use strict;

use DBI;
use constant DB_SOCKET => '/var/run/mysqld/mysqld.sock'; # Socket for mysql
use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );



my ($db_host, $db_name, $db_user, $db_pw); # Database details
my ($step);                                # Step in ins_id
my $hostname;

GetOptions(
    'dbhost=s' => \$db_host, # Database host name
    'dbname=s' => \$db_name, # Database name
    'dbuser=s' => \$db_user, # Database user
    'dbpass=s' => \$db_pw, # Database p/w
    'hostname=s' => \$hostname, # Host name
    'step=s' => \$step,    # Step in ins_id
           ) or die "Unable to parse arguments.\n";
die "Unknown option: @ARGV\n" if @ARGV;
die "Required options: --dbhost --dbname --dbuser --dbpass --step\n"
    unless defined $db_host
    and defined $db_name
    and defined $db_user
    and defined $db_pw
    and defined $step;

unless (defined $hostname) {
    $hostname = `hostname`;
    chomp $hostname;
}


# Database connection
my $db = DBI->connect( "DBI:mysql:database=$db_name;host=$db_host;mysql_socket=" . DB_SOCKET(),
                       $db_user,
                       $db_pw,
                       { RaiseError => 1, AutoCommit => 1 }
                       ) or die "Unable to connect to database: $DBI::errstr";

{
    my $old = select(STDOUT);
    $| = 1;
    select($old);
}

my $max_ins;                    # Maximum instance identifier
{
    my $sql = "SELECT MAX(ins_id) FROM instance";
    my $results = $db->selectcol_arrayref( $sql ) or die "Unable to execute SQL: $DBI::errstr";
    $max_ins = $$results[0];
}
print "MAX: $max_ins\n";



my $size = 0;                   # Sum of sizes
my $num = 0;                    # Number of files
for (my $i = 0; $i < $max_ins; $i += $step) {
    my $min = $i;               # Minimum instance for query
    my $max = $i + $step;       # Maximum instance for query
    print "Checking $min to $max...\n";

    my $sql = "SELECT uri FROM instance JOIN volume USING(vol_id) WHERE host = '$hostname' AND ins_id BETWEEN $min AND $max";

    my $results = $db->selectall_arrayref( $sql ) or die "Unable to execute SQL: $DBI::errstr";

    foreach my $result ( @$results ) {
        my $uri = $$result[0];
        $uri =~ s|^file:||;
        next unless defined $uri;
        my $bytes = -s $uri;
        next unless defined $bytes;
        $size += $bytes;
        $num++;
    }
}

print "$hostname: $size ($num files)\n";
