#!/usr/bin/perl -wt
#=============================================================================#
# (C) Denis Smirnov <mithraen@freesource.info)                    04 Aug 2006 #
#=============================================================================#
use DBI;
use strict;
use lib 'lib';
use Mithraen::OpenVZ::database;
use Mithraen::OpenVZ::config;

our $VERSION = '0.01';

my $database = '/var/spool/vzautolimit/cache.db';

my $vconf = new Mithraen::OpenVZ::config;
my $db    = new Mithraen::OpenVZ::database;

$db->init_db($database);
$db->update_ve_list($vconf);
$vconf->read_beancounters($db);

foreach ( $db->list_bugs ) {
    my @a = @{$_};
    $a[4] = int( $a[4] );
    print "vzctl set $a[0] --$a[1] $a[4] --save\n";
    local %ENV;
    `/usr/sbin/vzctl set $a[0] --$a[1] $a[4] --save 2>&1`;
    die unless $? == 0;
}

foreach ( $db->list_bugs_min ) {
    my @a = @{$_};
    $a[4] = int( $a[4] );
    print "vzctl set $a[0] --$a[1] $a[4] --save\n";
    local %ENV;
    `/usr/sbin/vzctl set $a[0] --$a[1] $a[4] --save 2>&1`;
    die unless $? == 0;
}

$vconf->ve_cfg_fix(undef);

sub min($$) {
    return $_[1] if $_[0] > $_[1];
    return $_[0];
}

foreach my $id ( $db->list_veids() ) {
    next if $id == 0;
    local %ENV;
    my $tmp = `/usr/sbin/vzquota show $id 2> /dev/null`;
    die unless $? == 0;
    $tmp =~ tr/\*/ /;
    my @tmp   = split /\n\s*/, $tmp;
    my @space = split /\s+/,   $tmp[1];
    my @inode = split /\s+/,   $tmp[2];
    my $i_limit = min( $inode[2], $inode[3] );    # inodes limit
    my $s_limit = min( $space[2], $space[3] );    # space limit
    my $i_p = ( $inode[1] / $i_limit * 100 );
    my $s_p = ( $space[1] / $s_limit * 100 );

    if ( $i_p > 80 or $s_p > 80 ) {
        print "$id inode " . $inode[1] . " " . $i_limit . " " . $i_p . "\n";
        print "$id space(1k) " . $space[1] . " " . $s_limit . " " . $s_p . "\n";
    }
}

