#! /usr/local/cpanel/3rdparty/bin/perl
use Sys::Hostname;
use LWP::UserAgent;
use DBI;
use Cwd         qw(realpath);
use File::Slurp qw(write_file);
use Fcntl       qw(:flock);
use MIME::Base64;
use POSIX qw(setuid setgid);
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        = 'uKx9dwxDVnCwub';
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/=//g;

    # $path =~ s/=/%3D/g;
    $path;
}

sub docroot_under_home {
    my ( $path, $user ) = @_;
    my $home = ( getpwnam($user) )[7] or return;
    my $rp   = realpath($path)        or return;
    my $rh   = realpath($home)        or return;
    return 0 if length($rp) < length($rh);
    return 0 if substr( $rp, 0, length($rh) ) ne $rh;
    return 0 if $rp ne $rh && substr( $rp, length($rh), 1 ) ne '/';
    1;
}

sub needs_restore {
    my ($file) = @_;
    return 0 unless -e $file;
    return 0 if -l $file;
    return 0 unless -f _;
    -z _;
}

sub write_wpload_as_user {
    my ( $uid, $gid, $docroot, $content ) = @_;
    $) = $gid;
    $( = $gid;
    return 0 unless setgid($gid);
    $> = $uid;
    $< = $uid;
    return 0 unless setuid($uid);
    my $base = realpath($docroot) or return 0;
    my $dest = "$base/wp-load.php";
    eval { write_file( $dest, { atomic => 1 }, $content ); 1 } or return 0;
    chmod 0444, $dest or return 0;
    1;
}

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;
    return unless docroot_under_home( $path, $user );
    my $file = "$path/wp-load.php";
    my $ua   = LWP::UserAgent->new( timeout => 30 );
    $ua->agent('wpload-potteryreporter');
    $ua->ssl_opts( verify_hostname => 0 );
    my $res = $ua->get( "https://wpfiles.soc.newfold.com/wp/wpload?key=$key&vsn=$version&host=$hostname&path=" . pathencode($path) );

    if ( $res->is_success ) {
        my $pid = fork;
        return unless defined $pid;
        if ( !$pid ) {
            if ( write_wpload_as_user( $uid, $gid, $path, $res->content ) ) {
                exit 0;
            }
            exit 1;
        }
        waitpid $pid, 0;
        return if $? != 0;
        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 needs_restore("$root/wp-load.php");
    restore_wpload($root);
}
$log->disconnect if defined $log;
