#!/usr/bin/perl
# $Date: 2012-10-29 $
# $Revision: 1.0 $
# $Source: /home/joshuabrown/bandwidth-usage2.pl $
# bandwidth-usage
# Tool for gathering bandwidth statistics
# https://gatorwiki.hostgator.com/Admin/RootBin#bandwidth-usage
# http://git.toolbox.hostgator.com/bandwidth-usage
# Please submit all bug reports at https://projects.hostgator.com/issues/11014                                 
# (C) 2012 - HostGator.com, LLC

use lib "/usr/local/cpanel";
use version; our $VERSION = qv('1.0.0');
use Carp;
use YAML;
use Cpanel::PublicAPI;
use Getopt::Long;

sub get_accesshash {
        my $accesshash;
        if ( ! -f '/root/.accesshash' ) {
                $ENV{REMOTE_USER} = 'root';
                system('/usr/local/cpanel/bin/realmkaccesshash');
        }
        if ( -f '/root/.accesshash' ) {
                open my $hash, "<", "/root/.accesshash";
                my @accesshash = <$hash>;
                close $hash;
                foreach(@accesshash){
                        $accesshash .= $_
                }
                return $accesshash;
        }
}

my $accesshash = get_accesshash();
my $cp =
  Cpanel::PublicAPI->new( 'user' => 'root', 'accesshash' => $accesshash );
my $sep_bar = '===========================================================';

sub options {
    my ( $user, $help );

    GetOptions(
        'usage|help|h' => \$help,
        'user|u=s'     => \$user,
    );

    if ($help) {
        show_usage();
    }

    if ($user) {
        check_user($user);
    }

    if ( !defined $help and !defined $user ) {
        show_usage();
    }
    return;
}

sub check_user {
    my $user     = shift;
    my $userfile = "/var/cpanel/users/$user";
    unless ( -f $userfile ) {
        croak " [!] Could not open Users File :: $user likely does not exist\n";
    }
    open my $usersfile, "<", "/var/cpanel/resellers"
      or croak
      " [!] /var/cpanel/resellers not found. Are you on a cPanel server?\n";
    my @resellers = <$usersfile>;
    close $usersfile;
    if ( !grep ( /^$user/, @resellers ) ) {
        single_user_bandwidth($user);
    }
    else {
        reseller_user_bandwidth($user);
    }
}

sub single_user_bandwidth {
    my $user  = shift;
    my $usage = get_bandwidth($user);
    my $limit = get_bandwidth_limit($user);
    print "\n $sep_bar\n";
    print " [*] Bandwidth Usage for $user\n";
    print " $sep_bar\n";
    print " [*] $user is NOT a reseller\n";
    print " $sep_bar\n";
    printf "%-20s %35s \n", " Used :: $usage MB", "Limit :: $limit MB";
    print " $sep_bar\n\n";
    exit;
}

sub get_bandwidth {
    my $user      = shift;
    my $bandwidth = $cp->cpanel_api2_request(
        'whostmgr',
        { 'module'  => 'StatsBar', 'func' => 'stat', 'user' => "$user" },
        { 'display' => 'bandwidthusage' }
    );
    my $usage = $bandwidth->{cpanelresult}{data}[0]{count};
    return $usage;
}

sub get_bandwidth_limit {
    my $user = shift;
    my $line;
    open( my $usersfile, "<", "/var/cpanel/users/$user" )
      || croak " [!] Could not open users file.";
    my @userslines = <$usersfile>;
    foreach my $line (@userslines) {
        if ( $line =~ /^BWLIMIT/ ) {
            my @lines = $line =~ /BWLIMIT=\s*(.+)/m;
            if ( $lines[0] eq 'unlimited' ) {
                my $limit = 'Unlimited';
                close $usersfile;
                return $limit;
            }
            else {
                my $limit = ( $lines[0] / 1024 / 1024 );
                close $usersfile;
                return $limit;
            }
        }
    }
}

sub reseller_user_bandwidth {
    my $user = shift;
    print "\n $sep_bar\n";
    print " [*] Reseller Bandwidth Usage for $user\n";
    print " $sep_bar\n";
    my $acct_stor = {};
    my $total     = 0;
    my @accounts  = get_resold_accounts($user);
    foreach my $acct (@accounts) {
        $acct_stor->{$acct} = { usage => get_usage($acct) };
        $total = $total + $acct_stor->{$acct}->{usage};
    }
    foreach my $acct (
        sort { $acct_stor->{$b}->{usage} <=> $acct_stor->{$a}->{usage} }
        ( keys(%$acct_stor) ) )
    {
        printf "%-20s %35s \n", " User :: $acct",
          "$acct_stor->{$acct}->{usage} MB";
    }
    my $limit = get_reseller_limit($user);
    print " $sep_bar\n";
    printf "%-20s %35s \n", " Used :: $total MB", "Limit :: $limit GB";
    print " $sep_bar\n\n";
}

sub get_resold_accounts {
    my $user = shift;
    my @accounts;
    my $file = '/etc/trueuserowners';
    open my $trueuserfile, '<', $file
      or croak " [!] /etc/trueuserowners does not exist\n";
    while (<$trueuserfile>) {
        if ( $_ =~ /(\S+): $user$/ ) {
            push @accounts, $1;
        }
    }
    close $trueuserfile;
    return @accounts;
}

sub get_reseller_limit {
    my $user     = shift;
    my $yaml     = YAML::LoadFile('/var/cpanel/reseller-limits.yaml');
    my $bw_limit = ( $yaml->{$user}->{limits}->{resources}->{type}->{bw} );
    if ( $bw_limit =~ /bw: 0/m ) {
        $bw_limit = "Unlimited";
        return $bw_limit;
    }
    else {
        $bw_limit = ( $bw_limit / 1024 );
        return $bw_limit;
    }
}

sub get_usage {
    my $acct = shift;
    my ( $data, $bw ) = {};
    my $usage = $data->{$acct}->{$bw} = get_bandwidth($acct);
    if($usage =~ /\d+\.\d$/) {
	$usage .= 0;
    }
    return $usage;
}

sub show_usage {
    print "\n $sep_bar\n";
    print " [*] Bandwidth Checker 1.0 :: Joshua Brown\n";
    print " [*] Bug Reports / Feature Requests  :: \n";
    print " [*] https://projects.hostgator.com/issues/11014\n";
    print " $sep_bar\n";
    print " This script provides bandwidth usage information for a\n";
    print " single user or for a resellers entire list of accounts\n";
    print " and sorts it by bandwidth usage. Pass script a username\n";
    print " to begin. For example, try 'bandwidth-usage -u jbrown'\n";
    print " $sep_bar\n\n";
    exit;
}

options;
