#!/usr/bin/perl -w

use strict;

use File::Copy;
use File::Temp qw(tempfile);


my $RRDTOOL = '/usr/local/bin/rrdtool';

my ( undef, $TMPFILE ) = tempfile( 'rrd_resize_XXXX', DIR => '/tmp', SUFFIX => '.rrd' );

my $CACTI_USER='cactiuser';

my @resize_rra = (
	[ GROW => 210400 ],
	[ GROW => 35400 ],
	[ GROW => 6600 ],
	[ GROW => 660 ],
	[ GROW => 210400 ],
	[ GROW => 35400 ],
	[ GROW => 6600 ],
	[ GROW => 660 ],
);

my $rrd_input = $ARGV[0];
my $rrd_output = $ARGV[1];

unless( $rrd_input and $rrd_output ) {
	die "$0: rrd_input rrd_output";
}

if( -e './resize.rrd' ) {
	die "./resize.rrd exists. please remove it";
}

copy( $rrd_input, $TMPFILE ) or die "Failed to copy tempfile: $!";

foreach my $rra ( 0 .. $#resize_rra ) {
	my ( $cmd, $rows ) = @{$resize_rra[$rra]};
	system( "$RRDTOOL resize $TMPFILE $rra $cmd $rows" );
	rename './resize.rrd', $TMPFILE or die "Failed to overwrite $TMPFILE: $!";
}

rename $TMPFILE, $rrd_output or die "Failed to write $rrd_output: $!";

my (undef,undef,$uid,$gid) = getpwnam( $CACTI_USER ) or die "Cannot fetch user: $!";
chown $uid, $gid, $rrd_output or die "Failed to chown: $!";

