#! /usr/bin/perl
###########
# editbwquota
# Update the BW quota for a cPanel user.
# http://git.toolbox.hostgator.com/editbwquota/pages/Home/
# http://git.toolbox.hostgator.com/editbwquota
# Please submit all bug reports at bugs.hostgator.com
#
# (C) 2011 - HostGator.com, LLC
###########
# by Rish
#
# Version 0.1: start.
#              
#

use strict;
use XML::Simple;
use Data::Dumper;

if ($#ARGV != 1) {
     print "editbwquota version 0.1\n";
     print "Usage: editbwquota <user> <new limit><M/G>\n";
     print "       Updates the bandwidth quota on the account.\n";
     exit 1;
}

if (eval {require cPanel::PublicAPI;}) {
	require cPanel::PublicAPI;
} else {
	print "[!] Failed to load the necessary modules for this script to function properly. Please install cPanel::PublicAPI via 'perl <(GET toolbox.hostgator.com/fixes/fix-cpanelapi)'\n";
	exit 1;
}

my $user = $ARGV[0];
my $newlimit = $ARGV[1];


if ( !-e "/var/cpanel/users/$user" ) {
     print "$user does not exist on the server.\n";
     exit 1;
}

if ($newlimit =~ m/([0-9]+)([MG]*)$/i) {
	my $number = $1;
	my $type = $2;

	if ($type eq "G" or $type eq "g") {
		$number *= 1024;
	}

	if ( !-s "/root/.accesshash" ) {
		$ENV{'REMOTE_USER'} = 'root';
		system('/usr/local/cpanel/bin/realmkaccesshash');
	}

	my $apic = cPanel::PublicAPI->new();
	my $response = $apic->whm_api('limitbw', { 'user' => $user, 'bwlimit' => $number }, 'xml');
	my $output = XMLin($response);

	if ($output->{'result'}->{'status'} == 1 ){
		print "[+] ".$output->{'result'}->{'statusmsg'}.".\n";
	} else {
		print "[!] ".$output->{'result'}->{'statusmsg'}.".\n";
	}
} else {
	print "[!] Improper input.\n";
	exit 1;
}
