#!/usr/bin/perl

use strict;
use warnings;

our $VERSION = '1.122320';

my $ips;
my $accounts = 0;
my $totalbound = 0;
my $totalunboundips = 0;
my $totalunboundaccounts = 0;
my $cpnat_map = undef;

my @userfiles = </var/cpanel/users/*>;

open my $RESERVEDIPREASONS, "<", "/etc/reservedipreasons" or warn("Unable to open '/etc/reservedipreasons': $!\n");
my @reserved = <$RESERVEDIPREASONS>;
close $RESERVEDIPREASONS;

open my $IFCONFIG, "ip a |" or die("Unable to run ifconfig: $!\n");
while(<$IFCONFIG>){
    if(m/inet\s(([0-9]{1,3}\.){3}[0-9]{1,3})/xms ){
        my $ip = $1 unless ( $1 =~ m/127\.0\.0\.1/xms );
        if($ip){
            $ips->{$ip}->{bound}++;
            my @reservedreasons = grep m/$ip=(.*)/xms, @reserved;
            foreach my $reason ( @reservedreasons ){
                $reason =~ m/$ip=(.*?)\s*$/xms;
                push @{$ips->{$ip}->{reservedreasons}}, $1;
            }
        }
    }
}
close $IFCONFIG;

if ( -s '/var/cpanel/cpnat' ) {
  open my $fh, '<', '/var/cpanel/cpnat';
  while (defined(my $line = <$fh>)) {
    chomp($line);
    my ( $private, $public) = split ( " ", $line);
    $cpnat_map->{$private} = $public;
  }
}

foreach my $userfile (@userfiles) {
    local $/;
    open my $FILE, $userfile or warn("Unable to open $userfile: $!\n");
    if(<$FILE> =~ m/\n?\s*IP\s*=\s*(.*?)\s*$/xms){
        $ips->{$1}->{used}++;
        $accounts++;
        $totalunboundaccounts++ unless $ips->{$1}->{bound};
    }
    close $FILE;
}

printf "%-10s %-15s %-15s\n", "Accounts", "IP", "Note";
foreach my $ip (sort keys %{$ips}){
    $ips->{$ip}->{bound} ? $totalbound++ : $totalunboundips++;
    if ($cpnat_map) {
      printf("%-10s %-15s", $ips->{$ip}->{used} || 0, "Private: $ip Public: $cpnat_map->{$ip}");
    }
    else {
      printf("%-10s %-15s", $ips->{$ip}->{used} || 0, $ip);
    }
    print( " *** IP NOT BOUND *** ") unless $ips->{$ip}->{bound};
    printf(" (%s)", join ' / ', @{$ips->{$ip}->{reservedreasons}}) if $ips->{$ip}->{reservedreasons};
    print "\n";
}
print  "-----------------------------------\n";
printf "         Total IPs found: %8i\n", scalar keys %{$ips};
printf "    Total accounts found: %8i\n", $accounts;
printf "     IPs bound to server: %8i\n", $totalbound;
printf " IPs not Bound to server: %8i\n", $totalunboundips;
printf " Accounts on unbound IPs: %8i\n", $totalunboundaccounts;
