#!/usr/bin/perl
#
# server-status v0.1
#
# This file checks the number of unique IP addresses connected to 
# our webserver. If a host is connected more than 20 times we do a
# hostname lookup (just because we can).
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# The GNU General Public License is available at:
# http://www.gnu.org/copyleft/gpl.html

# Create a user agent object
use LWP::UserAgent;
use Socket;

# Set up a new useragent
$ua = LWP::UserAgent->new;
$ua->agent("chkwww/0.1 ");

# Show only x connections or more
my $minconnections;
if ($#ARGV == -1) {
  $minconnections = 20;
} else {
  $minconnections = $ARGV[0];
}

# Do a HEAD request
my $req = HTTP::Request->new(GET => "http://mirror.leaseweb.com/server-status");

# Pass request to the user agent and get a response back
my $res = $ua->request($req);

# Check the outcome of the response
if ($res->is_success) {
  # Output results to user
  print "\n * Checking " . $res->header('server') . "\n";

  # Initialize the array
  my @ips;
  %ipcount = (); # clear the hash out  
  
  # Now to parse the actual content
  foreach my $line (split('\n', $res->content)) {
    if ($line =~ /<b>(\S+) connections<\/b>/) {
      # Total number of active connections
      print " - Total number of active connections: $1\n";
    } elsif ($line =~ /<tr><td class="string">\d+\.\d+\.\d+\.\d+<\/td><td class="int">/) {
      my $ip = (($line) =~ /<tr><td class="string">(\S+)<\/td><td class="int">/);
      $ip = $1;

      # Add IP to array
      push(@ips,$ip);
    }
  }

  # Count how many times we've seen each IP
  foreach my $ip (@ips) {
    $count{$ip} += 1;
  }

  print " - Hosts with $minconnections or more connections:\n";

  # Display results
  foreach my $ip (
    sort { $count{$a} <=> $count{$b} } keys %count
  ) {
    if ($count{$ip} > $minconnections - 1) {
      my $ipaddr = inet_aton($ip); 
      my $host = gethostbyaddr($ipaddr, AF_INET); 
      if ($host == "") {
        print "    $count{$ip}: $ip\n";
      } else {
        print "    $count{$ip}: $ip [$host]\n";
      }
    }
  }
} else {
  # Something went wonky
  print $res->status_line, "\n";
}

print "\n";
