#!/usr/bin/env perl

################################################################################
## write log to db
##
## Reads in the stdout generated by the disk_tool.pl script and dumps
## it into the database.  Should no longer be useful, since disk_tool.pl now
## has an integrated option to do that.  However, it was faster to write
## this than to restart the 'du's done by an old running copy already.
##
## NOTE: assumes the logs print sizes in megabytes!
##
################################################################################

use strict;
use warnings;

use Getopt::Long;

use lib $ENV{'NMI_LIB'} || "/nmi/lib";
use NmiConf;
use NmiTools;

my %conf = NmiConf::init( $main::opt_nmiconf );
use NmiDatabaseVariables;
require NmiDatabase;

my $line;
while( <> ) {
    my( $sizeInMegabytes, $fullPath ) = split( " " );
    if( ! defined( $sizeInMegabytes ) || ! defined( $fullPath ) ) {
        next;
        }
    
    my $gid = $fullPath;
    $gid =~ s#((/[^/]*)*/)##;
    print( $gid . "\n" );
    
    # FIXME: should also grab the 'archived' bit so that we automagically
    # update the proper column.
    my $query = qq/SELECT runid FROM Run WHERE gid = '$gid'/;
    my $handle = NmiDatabase::execute( $query );
    my $row = $handle->fetchrow_hashref();
    my $runid = $row->{ 'runid' };
    $handle->finish();
    print( $runid . "\n" );
    
    print( $sizeInMegabytes . "\n" );
    
    my $bytes = 1024 * 1024 * $sizeInMegabytes;
    my $insert = qq/INSERT INTO run_sizes SET runid = $runid, cleaned_size = $bytes /;
    $insert .= qq/ON DUPLICATE KEY UPDATE cleaned_size = $bytes/;
    print( $insert . "\n" );
    
    NmiDatabase::execute( $insert );
    }
