#!/usr/local/cpanel/3rdparty/bin/perl
use strict;
use warnings;
use v5.10;

use lib '/opt/eig_linux/lib';
use PHPUpgrader;
use PHPUpgrader::CpanelUtils;
use Data::Dumper;
use Getopt::Long qw(:config gnu_getopt);
use JSON::XS 'decode_json';
use YAML 'LoadFile';
use Sys::Hostname;
use IO::Socket::INET;

my $opts = {
    'debug' => 0,
    'all' => 0,
    'debug' => 0,
    'dryrun' => 0,
    'force' => 0,
};

usage() if(!GetOptions(\%{$opts},
    'dryrun|D',
    'upgrade',
    'revert',
    'get-versions',
    'get-upgrade-stats',
    'user|u=s',
    'all',
    'debug',
    'help|h',
    'old-only',
    'no-cache',
    'config=s',
    'submit',
    'force',
    'bluehost',
    )
);
usage() if($opts->{'help'});
my $hostname = hostname;
#validate some data and options
die 'Need to pass in user or set --all flag' if (!$opts->{'user'} && !$opts->{'all'});
my $cpanel = PHPUpgrader::CpanelUtils->new();
my $users = $cpanel->get_cusers();
for my $user (keys %{$users}) {
    delete $users->{$user} if ( -e "/var/cpanel/suspended/$user" );
    delete $users->{$user} if ( ! -d "/var/cpanel/userdata/$user" );
    delete $users->{$user} if $opts->{'bluehost'} && (! -f "/etc/maindata/$user.yaml" );
}
delete $users->{'eig1wp11'} if ( !defined $opts->{'user'} || $opts->{'user'} ne 'eig1wp11' );
 if ($opts->{'user'}) {
    die "User $opts->{'user'} not found\n" if (!$users->{$opts->{'user'}});
    $users = { $opts->{'user'} => $users->{$opts->{'user'}} };
}

my $version_counts;
#run the things
for my $user (sort(keys %{$users})) {
    if ($opts->{'get-versions'}) {
        get_versions($user);
    } elsif ($opts->{'get-upgrade-stats'}){
        get_upgrade_stats($user);
    } elsif ($opts->{'revert'}) {
        my $upgrader = new PHPUpgrader({
            'user' => $user,
            'dryrun' => $opts->{'dryrun'},
            'debug' => $opts->{'debug'},
        });
        $upgrader->revert_user();
    } elsif ($opts->{'upgrade'}) {
        my $upgrader = new PHPUpgrader({
            'user' => $user,
            'dryrun' => $opts->{'dryrun'},
            'debug' => $opts->{'debug'},
            'force' => $opts->{'force'},
        });
        $upgrader->upgrade_php();
    }
}
submit_graphite() if $opts->{'submit'};
exit;


sub get_versions{
    my $user = shift;
    my $versions;
    my $cachefile = "/opt/eig_linux/data/php_upgrader/$user.json";
    if (-f $cachefile && !$opts->{'no-cache'} && (((stat $cachefile)[9]) >= time - (60*60*24*2))){
        my $json = slurp($cachefile) or die "cache file $cachefile found but not readable\n";
        $versions = decode_json($json);
        $versions = $versions->{'current'};
    } else {
        eval {
            my $upgrader = new PHPUpgrader({
                'user' => $user,
                'dryrun' => $opts->{'dryrun'},
                'debug' => $opts->{'debug'},
            });
            $versions = $upgrader->get_domain_php_versions()
        };
        if ($@) {
            print "Could not get versions for $user\n";
            return -1;
        }
    }
    my $smallest_domain = get_lowest_version($versions);
    my $smallest_php =  $versions->{'domain'}->{$smallest_domain};
    $version_counts->{"php-$smallest_php"}++;
    if (!$opts->{'submit'}) {
        if ($opts->{'bluehost'}) {
            #we can get custid on bluehost, so lets do it
            my $main_data;
            eval{$main_data = LoadFile("/etc/maindata/$user.yaml");};
            printf "%s,%s,%s,%s,%s\n", $hostname,$user,$smallest_php,$smallest_domain,$main_data->{'cust_id'};
        } else {
            print "$hostname,$user,$smallest_php,$smallest_domain\n";
        }
    }
}

sub get_lowest_version {
    #Given a version hash returns the domain and version for the smallest php version
    my $versions = shift;
    my $smallest_domain = $versions->{'main_domain'};
    my $smallest_php =  $versions->{'domain'}->{$smallest_domain};
    foreach my $domain (keys %{$versions->{'domain'}}){
        if (!defined $smallest_php || $versions->{'domain'}->{$domain} < $smallest_php){
            $smallest_php = $versions->{'domain'}->{$domain};
            $smallest_domain = $domain;
        }
    }
    return $smallest_domain;
}

sub get_upgrade_stats {
    my $user = shift;
    my $versions;
    my $cachefile = "/opt/eig_linux/data/php_upgrader/$user.json";
    if (-f $cachefile && !$opts->{'no-cache'} && (((stat $cachefile)[9]) >= time - (60*60*24*2))){
        my $json = slurp($cachefile) or die "cache file $cachefile found but not readable\n";
        $versions = decode_json($json);
    }
    my $old_data_file = "/root/php_upgrades/php_upgrade_tracker.json";
    my $old_data = -f $old_data_file ?  eval{ decode_json(slurp($old_data_file)) }: {};
    $versions->{'initial'} = $old_data->{$user}->{'initial'} if defined  $old_data->{$user}->{'initial'};
    if (!defined $versions->{'initial'} || !defined $versions->{'current'}) {
        #print "no upgrade found for $user\n";
        return;
    }
    $versions->{'initial'}->{'main_domain'} //= $versions->{'current'}->{'main_domain'};
    my $lowest_initial_domain = get_lowest_version($versions->{'initial'});
    my $lowest_current_domain = get_lowest_version($versions->{'current'});

    #Find all the failures
    my $failed_domains;
    my $broken_site = 'NONE';
    for my $log_file ( "/var/log/php_upgrader.log", "/var/log/php_upgrader/user_logs/$user.log"){
        next if ! -f $log_file;
        open(my $fh, '<', $log_file);
        while (my $line = <$fh>) {
            next unless $line =~ m/\[FAIL\].*failed post checks.*\s(([A-Za-z0-9][A-Za-z0-9\-]{0,62}(\.|\b)){2,})/;
            my $domain = $1;
            if (defined $versions->{'initial'}->{'domain'}->{$domain} && defined $versions->{'current'}->{'domain'}->{$domain}){
                if ($versions->{'initial'}->{'domain'}->{$domain} == $versions->{'current'}->{'domain'}->{$domain}) {
                    $failed_domains->{$domain} = 'failed_back';
                } else {
                    $failed_domains->{$domain} = 'force_ugraded';
                    if (!$broken_site || $domain eq $versions->{'initial'}->{'main_domain'} ) {
                        $broken_site = $domain;
                    }
                }
            }
        }
    }

    #print the data now
    my $custid = '';
    if ($opts->{'bluehost'}) {
        #we can get custid on bluehost, so lets do it
        my $main_data;
        eval {$main_data = LoadFile("/etc/maindata/$user.yaml");};
        $custid = ",$main_data->{'cust_id'}";
    }
    printf "%s,%s,%s,%s,%s$custid\n",
            $hostname,
            $user,
            $versions->{'initial'}->{'domain'}->{$lowest_initial_domain},
            $versions->{'current'}->{'domain'}->{$lowest_current_domain},
            $broken_site,
           ;

}

sub submit_graphite {
    die "Unable to open collectd conf" if ( !-f '/etc/collectd.conf');
    open my $fh, '<', '/etc/collectd.conf' or die "Unable to open file\n";
    my $content = join("\n", <$fh>);
    close $fh;
    my $now = time();
    my $statname = hostname;
    $statname =~ s/\./_/g;
    $content =~ m/(\w\.\w+\.\w+\.\w+\.)/xms;
    my $header = $1;
    $content =~ m/(50\.\d{1,3}\.\d{1,3}\.\d{1,3})/xms;
    my $ip = $1;
    my $prefix = sprintf("%s%s.php-versions",
                        $header,
                        $statname
                        );
    #we need to send it someplace
    my $socket = new IO::Socket::INET (
            PeerHost => $ip,
            PeerPort => '2003',
            Proto => 'udp',
    );

    #send the data
    my $buffer = '';
    my $limit = 1024;
    foreach my $key (sort keys %$version_counts){
        my $nextline = sprintf("%s.%s %.2f %d\n",$prefix,$key, $version_counts->{$key},$now);
        #see if this message puts us over the limit
        if( length($buffer) + length($nextline) > $limit ){
            $socket->send($buffer);
            $buffer = '';
        }
        $buffer .= $nextline;
    }
    if(length($buffer) > 0){
        $socket->send($buffer);
    }
}

sub usage {
    my $spacing = 3;
    my $spaces = " "x($spacing);
    print("\n");
    printf("  $0 [options]\n");
    printf("  OPTIONS:\n");
    printf("\t--%-29s$spaces%s\n", "debug", "enable debug output");
    printf("\t--%-29s$spaces%s\n", "dryrun", "dont actually make any changes");
    printf("\t--%-29s$spaces%s\n", "help", "show this help screen, and exit");
    printf("\t--%-29s$spaces%s\n", "upgrade", "run the updates");
    printf("\t--%-29s$spaces%s\n", "revert", "revert php updates");
    printf("\t--%-29s$spaces%s\n", "get-versions", "get smallest php version of each user");
    printf("\t--%-29s$spaces%s\n", "no-cache", "don't use cached php versions and query fresh ones");
    printf("\t--%-29s$spaces%s\n", "user=<username>", "restrict actions to this user");
    printf("\t--%-29s$spaces%s\n", "all", "run for all users on the box");
    print("\n");
    exit(33);
}
sub slurp {local$/=<>if local@ARGV=@_}
