#! /usr/local/cpanel/3rdparty/bin/perl
use Sys::Hostname;
use LWP::UserAgent;
use DBI;
use Fcntl qw(:flock);
use MIME::Base64;
use strict;
use warnings;
my $hostname = hostname;
my $dbdir = "/var/lib/eig/dc";
my $pluginfile = "$dbdir/plugins";
my $logfile = "/opt/eig_linux/etc/corereplace.sqlite";
my $key = 'a-sd9ifjxxz';
my $now = time;
open my $runonce, '<', $0 or die "Unable to open self for reading $0 : $!";
flock $runonce, LOCK_EX | LOCK_NB or exit;

my (%versions, %roots, %users, $log);
{
    my $dbh = DBI->connect("dbi:SQLite:dbname=$pluginfile", undef, undef, { RaiseError => 1 });
    %roots = map { $versions{$_->[1]} = $_->[0]; $users{$_->[1]} = $_->[2]; $_->[1], 1 } @{$dbh->selectall_arrayref("select wpver,root,user from plugins")};
    $dbh->disconnect;
}

sub openlog {
    return if defined $log;
    $log = DBI->connect("dbi:SQLite:dbname=$logfile", undef, undef, { RaiseError => 1 });
    $log->do(<<SQL);
CREATE TABLE IF NOT EXISTS log (
    user TEXT NOT NULL,
    path TEXT NOT NULL,
    count INT NOT NULL,
    last INT NOT NULL,
    PRIMARY KEY (path)
);
SQL
}

sub updatelog {
    my ($user, $file) = @_;
    $file =~ s,//+,/,g;
    my @res = @{$log->selectall_arrayref('SELECT * FROM log WHERE path=?', { Slice => {} }, $file)};
    if (@res) {
        $log->do('UPDATE log SET count = ? WHERE path = ?', {}, $res[0]->{count}+1, $file);
    } else {
        $log->do('INSERT INTO log VALUES (?, ?, ?, ?)', {}, $user, $file, 1, $now);
    }
}

sub pathencode {
    my ($path) = @_;
    $path = encode_base64($path);
    $path =~ s/\n//g;
    $path =~ s/=/%3D/g;
    $path
}

sub restore_wpload {
    my ($path) = @_;
    my $version = $versions{$path};
    my $user = $users{$path};
    my ($uid, $gid) = (getpwnam($user))[2,3];
    return unless $version =~ /^[\d.]+$/; # could be '?'
    return unless $uid && $gid;
    my $file = "$path/wp-load.php";
    my $ua = LWP::UserAgent->new;
    $ua->agent('wpload-potteryreporter');
    $ua->ssl_opts(verify_hostname => 0);
    my $res = $ua->get("https://scripts.hostgator.com/~sec/wpfiles/wpload.nim?key=$key&vsn=$version&host=$hostname&path=".pathencode($path));
    if ($res->is_success) {
        open my $f, '>', $file or return;
        print {$f} $res->content;
        close $f;
        chmod 0444, $file;
        chown $uid, $gid, $file;
        print STDERR "$now RESTORED wp-load.php for WordPress $version : $path\n";
        openlog();
        updatelog($user, $file);
    } else {
        print STDERR "$now FAILED wp-load.php for WordPress $version : $path\n";
    }
}

open STDERR, '>', '/dev/null' unless -t \*STDIN;
for my $root (keys %roots) {
    next unless -z "$root/wp-load.php";
    restore_wpload($root);
}
$log->disconnect if defined $log;
