#!/usr/bin/perl -w
###########
## should_i_migrate.pl
## This script reports stats of a shared/reseller server and using pre-determined limits makes a recommendation on whether or not the server in question 
## is a good migration candidate. If the server is too overloaded or has reached limits that would be setting off alerts in Zabbix, this script will 
## recommend that the server is NOT currently a good candidate for an account migration.
##
## If the script recommends not to migrate, then you may want to get with a monitor or supervisor to investigate why now is not a good time to migrate to this server.
##
## https://gatorwiki.hostgator.com/Admin/Should_i_migrate
## http://git.toolbox.hostgator.com/should_i_migrate/should_i_migrate
## Please submit all bug reports at bugs.hostgator.com
##
## (C) 2013 - HostGator.com, LLC
############

use strict;
use Data::Dumper;
use Carp;
use Sys::Hostname;

my $script = {
    name => 'Should I Migrate?',
    desc => 'Script to suggest whether or not you should migrate a new account to a given server',
    version => '0.2.0',
    author => 'Grayson Paynter',
    report => 'Jira',
};

#### LIMITS ####
my $var_inodes_limit = 90;
my $home_inodes_limit = 93;
my $var_disk_limit = 90;
my $home_disk_limit = 85;
my $bigmac_size_warning = 3.5;
################

my $ok_to_migrate = 1;
my @warnings = ();

main();
sub main {
    _print_header();
    my ($hostname,$ip) = _get_basic_system_info();
    my ($numcpus) = _get_cpu_info();
    my ($sys_uptime,$apache_uptime,$mysql_uptime) = _get_uptimes();
    my ($loadavg1,$loadavg5,$loadavg15) = _get_loadavg($numcpus);
    _get_disk_stats();
    _get_inode_count();
    _final_tally(@warnings);
    _end();
}

sub _print_header {
    # Print out the header information
    print "\n\033[1m" . $script->{name} . " \033[0m- " . $script->{desc} . "\n";
    print "\033[1mVersion:\033[0m " . $script->{version} . " - \033[1mAuthor:\033[0m " . $script->{author} . "\n";
    print "Report bugs to <\033[1m" . $script->{report} . "\033[0m>\n";
    print "\033[1m--------------------------------------\033[0m\n";
}

sub _get_basic_system_info {
    my $hostname = hostname || `uname -n`;
    _print_line("Hostname: $hostname");

    my $ip = `hostname -i`;
    chomp $ip;
    _print_line("Primary IP: $ip");
    return ($hostname,$ip);
}

sub _get_cpu_info {
    my $numcpus = `grep -c proc /proc/cpuinfo`;
    chomp $numcpus;
    
    if (!$numcpus) {
        croak "Unable to determine the number of CPUs!";
    }

     _print_line("CPUs: $numcpus");

    return $numcpus;
}

sub _print_line {
    my ($line) = @_;
    print "\033[1m[*]\033[0m " . $line . "\n";
    }

    sub _alert {
    my ($line) = @_;
    print "\033[1m[!]\033[0m " . $line . "\n";
}

sub _get_uptimes {

    my @sys_uptime;

    open(my $UPTIME,'/proc/uptime') or croak "unable to open /proc/uptime";
    while (<$UPTIME>) {
        @sys_uptime = split(/ /,$_);
    }
    close($UPTIME);

    chomp(@sys_uptime);
    my $seconds_up = int($sys_uptime[0]);
    my $now = time;
    my $then = $now - $seconds_up;
    my $date = localtime($then);

    my $uptime = sprintf "%d days, %d hours, %d minutes and %d seconds", (gmtime $seconds_up)[7,2,1,0];
    _print_line("System Uptime: $uptime");
    _print_line("Last restart: $date");

    my $cmd = "service httpd status 2> /dev/null| grep -Po 'Server uptime:.+\$'";
    my $apache_uptime = `$cmd`;
    chomp $apache_uptime;
    _print_line("Apache Uptime: $apache_uptime");

    my $mysql_uptime = `mysqladmin status 2> /dev/null | awk '{print \$2}'`;
    _print_line("Mysql Uptime: $mysql_uptime");

    return ($seconds_up,$apache_uptime,$mysql_uptime);
}

sub _get_loadavg {
    my ($numcpus) = @_;

    my @loadavg;
    open(my $LOADAVG,"/proc/loadavg") or croak "unable to open /proc/loadavg";
    while(<$LOADAVG>) {
        @loadavg = split(/ /,$_);
    }
    close($LOADAVG);

    my $loadavg1 = $loadavg[0];
    my $loadavg5 = $loadavg[1];
    my $loadavg15 = $loadavg[2];

    _print_line("LoadAvg: $loadavg1 $loadavg5 $loadavg15");

    return ($loadavg1,$loadavg5,$loadavg15);
}

sub _get_disk_stats {
    my $var;
    my $homes = {};

    print "\n";
    _print_line("\033[1;34mDisk Stats\033[m");
    my @df = split(/^/,`df -h`);
    chomp @df;
    foreach my $item (@df) {
        if($item =~ /^.*(\d+)%\s+\/var$/) {
            $var = $1;
            _print_line($item);
        } elsif ($item =~ /^.+\s+(\d+(\.\d+)?).\s+(\d+(\.\d+)?).\s+(\d+).\s+(\d+)%\s+\/(home(?:|\d+))$/) {
            $homes->{$7}->{size} = $3; 
            $homes->{$7}->{used} = $4;
            $homes->{$7}->{free} = $5;  
            $homes->{$7}->{percent} = $6;  
            _print_line($item);
        }
    }

    if ($var && $var > $var_disk_limit) {
        my $msg = "/var is > $var_disk_limit% full!";
        push(@warnings,$msg);
    }
    my $bigmacwarning = 0;
    foreach my $dir (keys(%$homes)) {
        if ($homes->{$dir}->{size} < $bigmac_size_warning && !$bigmacwarning) {
            my $msg = "Server is not a BigMac. Verify the account you are migrating is less than 100GB or migrate them to a BigMac.";
            push(@warnings,$msg);
            $bigmacwarning = 1;
        }
        if ($homes->{$dir}->{percent} > $home_disk_limit) {
            my $msg = "$dir is > $home_disk_limit% full! ($homes->{$dir}->{percent}%)";
            push(@warnings,$msg);
        }
    }
}

sub _get_inode_count {
    my $var;
    my $homes = {};

    _print_line("Inodes");
    my @df = split(/^/,`df -hi`);
    chomp @df;
    foreach my $item (@df) {
        if($item =~ /^.*(\d+)%\s+\/var$/) {
            $var = $1;
            _print_line($item);
        } elsif ($item =~ /^.+\s+(\d+)%\s+\/(home(?:|\d+))$/) {
            $homes->{$2} = $1; 
            _print_line($item);
        }
    }

    if ($var && $var > $var_inodes_limit) {
        my $msg = "/var Inodes are > $var_inodes_limit% !";
        push(@warnings,$msg);
    }

    foreach my $dir (keys(%$homes)) {
        if ($homes->{$dir} > $home_inodes_limit) {
            my $msg = "$homes->{dir} inodes are > $home_inodes_limit%";
            push(@warnings,$msg);
        }
    }

}

sub _final_tally {
    my (@warnings) = @_;
    my $numwarnings = @warnings;
    # Essentially, we want to know if we're OK to migrate to this box
    # If we have 1 or more total warnings, recommend NOT migrating to this box
    if ($numwarnings > 0) {
        print "\n";
        _alert("\033[1;31m$numwarnings warnings found!\033[m");
        foreach my $item (@warnings) {
            _alert($item);
        }
        print "\n";
        _alert("\033[1;31mReview the warnings noted before migrating. You may need to change the user's home directory if they are on a partition that is low.\033[m");
        _alert("\033[1;31mIf you have any questions on server health reach out to EMC for assistance.\033[m");

    } elsif ($ok_to_migrate) {
    # Else: Should be OK to migrate here
        print "\n";
        _print_line("\033[1;32m0 warnings, you should be OK to migrate a new account to this server.\033[m");
    } else {
        print Dumper "wat";
    }
}

sub _end {
    _print_line("End.");
}

