#!/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 File::Basename;
use Sys::Hostname;
use IO::Socket::INET;

my $opts = {
    'debug' => 0,
    'all' => 0,
    'debug' => 0,
    'dryrun' => 0,
    'force' => 0,
};
my $pid_file = "/opt/eig_linux/data/php_upgrader/phpupgrader.pid";

usage() if(!GetOptions(\%{$opts},
    'dryrun|D',
    'upgrade',
    'revert',
    'get-versions',
    'get-upgrade-stats',
    'user|u=s',
    'all',
    'debug',
    'help|h',
    'no-cache',
    'submit',
    'force',
    'bluehost',
    'create-job',
    'run-jobs',
    'reseller',
    'stop-inheriting',
    'convert-legacy-handlers',
    'check-legacy-handlers',
    'id=s',
    'last',
    'allow-suspended',
    'find-subdir-docroots',
    'sync-handlers',
    )
);
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'} && !$opts->{'run-jobs'});
make_pid() if ($opts->{'upgrade'} || $opts->{'revert'} || $opts->{'stop-inheriting'});
my $cpanel = PHPUpgrader::CpanelUtils->new();
my $users = $cpanel->get_cusers();
my $job_folder = "/var/spool/php_upgrades";
mkdir $job_folder if ! -d $job_folder;
for my $user (keys %{$users}) {
    delete $users->{$user} if (( -e "/var/cpanel/suspended/$user" ) && !$opts->{'allow-suspended'}); 
    delete $users->{$user} if ( ! -d "/var/cpanel/userdata/$user" );
    delete $users->{$user} if $opts->{'bluehost'} && (! -f "/etc/maindata/$user.yaml" );
}
if ( -f "/opt/eig_linux/data/php_upgrader/ignored_users"){
    open (my $fh, '<', "/opt/eig_linux/data/php_upgrader/ignored_users");
    while (my $ignored_user = <$fh>){
        chomp($ignored_user);
        delete $users->{$ignored_user} if $users->{$ignored_user};
    }
}
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 @queue;
if ($opts->{'run-jobs'} ){
    my @jobs = glob("$job_folder/*");
    foreach my $job (@jobs) {
    my $user = basename $job;
        if ( $users->{$user} ) {
            push @queue,$user;
        } else {
            print "Deleting invalid job $job\n";
            unlink "$job_folder/$user";
        }
    }
}
my $true_user_owners;
if ($opts->{'reseller'}) {
    open (my $fh, '<', '/etc/trueuserowners');
    while (my $line = <$fh>){
        chomp($line);
        if ($line =~ m/(\w+):\s+(\w+)/g) {
            my $account = $1;
            my $owner = $2;
            $true_user_owners->{$account} = ($owner =~ m/^root$/) ? $account : $owner;
        }
    }
}

my $version_counts;
#run the things
for my $user (sort(keys %{$users})) {
    next if ($opts->{'run-jobs'} && ! grep(/^$user$/,@queue));
    if ($opts->{'get-versions'}) {
        get_versions($user);
    } elsif ($opts->{'get-upgrade-stats'}){
        get_upgrade_stats($user);
    } elsif ($opts->{'check-legacy-handlers'}){
        check_legacy_handlers($user);
    } elsif ($opts->{'revert'}) {
        my $upgrader = new PHPUpgrader({
            'user' => $user,
            'dryrun' => $opts->{'dryrun'},
            'debug' => $opts->{'debug'},
            });
        my $res;
        my $cachefile = "/opt/eig_linux/data/php_upgrader/$user.json";
        if ($opts->{'last'} && -f "$cachefile"){ 
            my $json = slurp($cachefile) or die "cache file $cachefile found but not readable\n";
            my $data = decode_json($json);
            $opts->{'id'} = $data->{'lastrun'} || undef;
        }
        eval { $res = $upgrader->revert_user($opts->{'id'}); };
        unlink "$job_folder/$user" if -f "$job_folder/$user" && $res->{'upgrade_status'} =~ m/complete/i;
    } elsif ($opts->{'upgrade'}) {
        my $upgrader = new PHPUpgrader({
            'user' => $user,
            'dryrun' => $opts->{'dryrun'},
            'debug' => $opts->{'debug'},
            'force' => $opts->{'force'},
            });
        my $res;
        eval { $res = $upgrader->upgrade_php(); };
        unlink "$job_folder/$user" if -f "$job_folder/$user" && $res->{'upgrade_status'} =~ m/(complete|failure)/i;
    } elsif ($opts->{'stop-inheriting'}) {
        my $upgrader = new PHPUpgrader({
            'user' => $user,
            'dryrun' => $opts->{'dryrun'},
            'debug' => $opts->{'debug'},
            });
        my $res;
        eval { $res = $upgrader->stop_inheriting(); };
        unlink "$job_folder/$user" if -f "$job_folder/$user" && $res->{'upgrade_status'} =~ m/(complete|failure)/i;
    } elsif ($opts->{'convert-legacy-handlers'}) {
        my $upgrader = new PHPUpgrader({
            'user' => $user,
            'dryrun' => $opts->{'dryrun'},
            'debug' => $opts->{'debug'},
            });
        my $res;
        eval { $res = $upgrader->convert_legacy_handlers(); };
        unlink "$job_folder/$user" if -f "$job_folder/$user" && $res->{'upgrade_status'} =~ m/(complete|failure)/i;
    } elsif ($opts->{'sync-handlers'}) {
        my $upgrader = new PHPUpgrader({
            'user' => $user,
            'dryrun' => $opts->{'dryrun'},
            'debug' => $opts->{'debug'},
            });
        my $res;
        eval { $res = $upgrader->sync_handlers(); };
        unlink "$job_folder/$user" if -f "$job_folder/$user" && $res->{'upgrade_status'} =~ m/(complete|failure)/i;
    } elsif ($opts->{'find-subdir-docroots'}) {
        my $upgrader = new PHPUpgrader({
            'user' => $user,
            'dryrun' => $opts->{'dryrun'},
            'debug' => $opts->{'debug'},
            });
        my $res;
        eval { $res = $upgrader->find_subdir_docroots(); };
        unlink "$job_folder/$user" if -f "$job_folder/$user";
    } elsif ($opts->{'create-job'}) {
        if (! -f "$job_folder/$user"){
            open (my $fh, '>', "$job_folder/$user");
            close $fh;
        }
    }
}
submit_graphite() if $opts->{'submit'};
unlink $pid_file if ($opts->{'upgrade'} || $opts->{'revert'} || $opts->{'stop-inheriting'});
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"}++;
    my $reseller_string = "";
    if ($opts->{'reseller'}) {
        $reseller_string = defined $true_user_owners->{$user} ? ",$true_user_owners->{$user}" : ",";
    }
    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$reseller_string\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 check_legacy_handlers {
    my $user = shift;
    my $cachefile = "/opt/eig_linux/data/php_upgrader/$user.json";
    my $versions;
    if (-f $cachefile ) {
        my $json = slurp($cachefile) or die "cache file $cachefile found but not readable\n";
        $versions = decode_json($json);
    }
    return unless defined $versions->{'current'}->{'htaccess_handler'};
    for my $path (keys %{$versions->{'current'}->{'htaccess_handler'}}){
        my $value = $versions->{'current'}->{'htaccess_handler'}->{$path};
        if ($value && !($value =~ m/ea-php/)){
            print "$user,$path,$value\n";
        }
    }
    if (defined $versions->{'subdir_docroots'}->{'htaccess_handler'}){
        for my $path (keys %{$versions->{'subdir_docroots'}->{'htaccess_handler'}}){
            my $value = $versions->{'subdir_docroots'}->{'htaccess_handler'}->{$path};
            if ($value && !($value =~ m/ea-php/)){
                print "$user,$path,$value,SUBDIR\n";
            }
        }
    }
}

sub get_upgrade_stats {
    my $user = shift;
    my $versions;
    my $cachefile = "/opt/eig_linux/data/php_upgrader/$user.json";
    if (-f $cachefile ) {
        my $json = slurp($cachefile) or die "cache file $cachefile found but not readable\n";
        $versions = decode_json($json);
    }
    if ($opts->{'last'} && $versions->{'lastrun'}){ 
        $versions->{'initial'} = $versions->{'runs'}->{$versions->{'lastrun'}}->{'initial'}; 
    } 
    if (!defined $versions->{'initial'} || !defined $versions->{'current'}) {
        #print "no upgrade found for $user\n";
        return;
    }
    return unless defined $versions->{'runs'};
    $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 @sorted_runs = sort { $versions->{'runs'}->{$a} <=> $versions->{'runs'}->{$a} } keys %{$versions->{'runs'}};
    my $latest_run = $versions->{'runs'}->{pop(@sorted_runs)};
    my $broken_site = 'NONE';
    if (defined $latest_run->{'upgrade_force'}) {
    if (defined $latest_run->{'upgrade_force'}->{$versions->{'initial'}->{'main_domain'}} ){
        $broken_site = $versions->{'initial'}->{'main_domain'};
    } else {
        my @forced_domains = keys %{$latest_run->{'upgrade_force'}};
        $broken_site = shift(@forced_domains);
    }
    }

    #print the data now
    my $optional_fields = '';
    if ($opts->{'bluehost'}) {
        #we can get custid on bluehost, so lets do it
        my $main_data;
        eval {$main_data = LoadFile("/etc/maindata/$user.yaml");};
        $optional_fields .= ",$main_data->{'cust_id'}";
    }
    if (defined $versions->{'lastrun'}){ 
        $optional_fields .= ",$versions->{'runs'}->{$versions->{'lastrun'}}->{'date'}";
    } 
    printf "%s,%s,%s,%s,%s$optional_fields\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',
    );
    foreach my $ver (52, 53, 54, 55, 56, 70, 71, 72, 73, 74)  {
        $version_counts->{"php-$ver"} ||= 0;
    }
    #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 make_pid {
    my $alive;
    my $pid;
    if (-f $pid_file ) {
        chomp($pid = slurp($pid_file));
        die "Found an active pid for php_upgrader: $pid\n" if ($pid && (kill 0, $pid));
    }
    open (my $fh, '>', $pid_file);
    print $fh "$$\n";
    close $fh;
}

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", "Don't 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", "force", "Force the upgrades, even if the site fails post checks");
    printf("\t--%-29s$spaces%s\n", "revert", "Revert php updates");
    printf("\t--%-29s$spaces%s\n", "id=<runid>", "Used with revert to restore from a specific run only");
    printf("\t--%-29s$spaces%s\n", "get-versions", "Get smallest php version of each user");
    printf("\t--%-29s$spaces%s\n", "bluehost", "Only show accounts that have bluehost custids and show the custids");
    printf("\t--%-29s$spaces%s\n", "reseller", "Show the true user owner for the account");
    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");
    printf("\t--%-29s$spaces%s\n", "create-job", "Creates a job for the ugprade only");
    printf("\t--%-29s$spaces%s\n", "run-jobs", "Runs the actiosn for all the jobs in queue. Used in conjunction with upgrade or revert");
    printf("\t--%-29s$spaces%s\n", "stop-inheriting", "Makes sure a given user isn't inheriting PHP from /, and specifies the php handler in their roots instead");
    printf("\t--%-29s$spaces%s\n", "convert-legacy-handlers", "Convert any domains using a legacy php handler that has an equivilant EA one to EA instead");
    printf("\t--%-29s$spaces%s\n", "check-legacy-handlers", "Find any domains using non-EA PHP handlers");
    printf("\t--%-29s$spaces%s\n", "last", "Process a reversion or data collection from the last upgrade run only");
    printf("\t--%-29s$spaces%s\n", "allow-suspended", "Allow suspended uses to be processesd"); 
    printf("\t--%-29s$spaces%s\n", "find-subdir-docroots", "Find docroots with .htaccess handlers that are within a subdir of a docroot");
    printf("\t--%-29s$spaces%s\n", "sync-handlers", "Sync any handlers in .htaccess to cpanel"); 
    print("\n");
    exit(33);
}
sub slurp {local$/=<>if local@ARGV=@_}
