#! /usr/bin/env perl
use Sys::Hostname;
use LWP::UserAgent;
use Getopt::Long;
use DBI;
use Sys::Syslog;
use URI::Encode qw(uri_decode);
use strict;
use warnings;
my $hostname = hostname;

sub usage {
    die "usage: $0 [FLAGS] --campaign=CAMPAIGN --plugin=PLUGIN --version=VERSION [--where=WHERE]
or...: $0 [FLAGS] --campaign=CAMPAIGN --core --minor [--where=WHERE]

FLAGS
  --premium          # don't add --skip-plugins to wpcli command
  --skip-suspended
  --skip-backup
  --verbose          # print commands before running them
  --force            # pass onto wp-cli
  --install=URL      # 'wp plugin install URL'
  --chance=N         # exit unless a random number [0..100) is less than N
  --noretry          # skip upgrades already attempted
  --skip=PLUGIN      # don't upgrade plugin if site also has this plugin
  --require=PLUGIN   # only upgrade plugin if site also has this plugin
  --theme=THEME      # upgrade a theme, instead of a plugin

  --followup=CAMPAGIN  # only attempt upgrades if previously attempted an
                       # upgrade as part of this campaign

CAMPAIGN
  A unique identifier for related plugin upgrades, for tracking purposes.

PLUGIN
  The plugin 'slug', as it appears in the database or wp-content/plugins path,
  or wordpress.org URL, f.e.
    themegrill-demo-importer (for ThemeGrill Demo Importer)
    wordpress-seo (for Yoast SEO)
    wpforms-lite (for Contact Form by WPForms)

WHERE
  Arbitrary SQL syntax that's injected into the query used to select
  plugins to upgrade. No care is taken to avoid malicious SQL.

  The base query:
    SELECT user,db,root FROM plugins WHERE plugin='plugin'

  The query with --where=\"pver <> '3.9.4'\":
    SELECT user,db,root FROM plugins WHERE plugin='plugin' AND pver <> '3.9.4'

VERSION
  Now *required* unless ill-advised --minor or --patch arguments are used.
  Stats only syslogged with --version=
";
}

my $statuskey = 'aJcb55pgZ1ir6Y';
my $cphp72 = '/opt/cpanel/ea-php72/root/usr/bin/php';
my $cphp74 = '/opt/cpanel/ea-php74/root/usr/bin/php';
my (%options, %skiproots, %requireroots, $version, @users);
my ($upgrades, $misses) = (0, 0);
my $now = time;
@ARGV = map { uri_decode $_ } @ARGV; # fix tanium uri-encoding
GetOptions(
    "campaign=s" => \$options{campaign},
    "skip-suspended" => \$options{skipsuspended},
    "skip=s" => \$options{skip},
    "require=s" => \$options{require},
    "skip-backup" => \$options{skipbackup},
    "plugin=s" => \$options{plugin},
    "core" => \$options{core},
    "where=s" => \$options{where},
    "minor" => \$options{minor},
    "patch" => \$options{patch},
    "version=s" => \$options{version},
    "premium" => \$options{premium},
    "verbose" => \$options{verbose},
    "force" => \$options{force},
    "install=s" => \$options{install},
    "chance=s" => \$options{chance},
    "noretry" => \$options{noretry},
    "followup=s" => \$options{followup},
    "theme=s" => \$options{theme},
) or usage;
if (defined $options{chance}) {
    my $n = $options{chance};
    usage unless $n =~ /^\d+$/ && $n >= 0 && $n <= 100;
    exit unless rand(100) < $n;
}
usage unless defined $options{campaign} && $options{campaign} =~ /^[\w-]+$/
    && (defined($options{plugin}) || defined($options{core}) || defined($options{theme}));
usage if defined($options{plugin}) && defined($options{core}); # one or the other
usage if defined($options{theme}) && defined($options{core});
usage if defined($options{plugin}) && defined($options{theme});
#usage if defined($options{core}) && !defined($options{minor}); # for now, only permit --minor core upgrades
$options{where} = "AND $options{where}" if defined $options{where};
$options{where} = "" unless defined $options{where};
$version = "--minor" if defined $options{minor};
$version = "--patch" if defined $options{patch};
$version = "--version=$options{version}" if defined $options{version};
usage unless defined $version;
my $skip = "--skip-plugins --skip-themes";
$skip = "--skip-themes" if defined $options{premium};
my $force = defined $options{force} ? "--force" : "";

my $dbh = DBI->connect("dbi:SQLite:dbname=/var/lib/eig/dc/plugins", undef, undef, { RaiseError => 1 });
my $uplog = DBI->connect("dbi:SQLite:dbname=/var/lib/eig/dc/massupgrades", undef, undef, { RaiseError => 1 });
$uplog->do(<<'SQL');
CREATE TABLE IF NOT EXISTS upgrades (
    root TEXT NOT NULL,
    plugin TEXT NOT NULL,
    campaign TEXT NOT NULL,
    updated TEXT NOT NULL
);
SQL
sub logattempt {
    my ($root) = @_;
    $uplog->do('INSERT INTO upgrades (root, plugin, campaign, updated) VALUES (?, ?, ?, datetime())', {}, $root, $options{plugin}, $options{campaign}) if defined $options{plugin};
    $uplog->do('INSERT INTO upgrades (root, plugin, campaign, updated) VALUES (?, ?, ?, datetime())', {}, $root, $options{theme}, $options{campaign}) if defined $options{theme};
    $uplog->do('INSERT INTO upgrades (root, plugin, campaign, updated) VALUES (?, ?, ?, datetime())', {}, $root, "wp core", $options{campaign}) if defined $options{core};
}
sub followup {
    my ($root, $other) = @_;
    my @rows = @{$uplog->selectall_arrayref('SELECT root FROM upgrades WHERE root=? AND campaign=?', {}, $root, $other)};
    return @rows > 0
}
sub attempted {
    my ($root) = @_;
    my $target = $options{plugin};
    $target = $options{theme} if defined $options{theme};
    $target = "wp core" if defined $options{core};
    my @rows = @{$uplog->selectall_arrayref('SELECT root FROM upgrades WHERE root=? AND plugin=? AND campaign=?', {}, $root, $target, $options{campaign})};
    return @rows > 0
}
END { $uplog->disconnect if defined $uplog }

if ($options{skip}) {
    %skiproots = map { @$_, 1 } @{$dbh->selectall_arrayref("SELECT DISTINCT root FROM plugins WHERE plugin=?", {}, $options{skip})};
}
if ($options{require}) {
    %requireroots = map { @$_, 1 } @{$dbh->selectall_arrayref("SELECT DISTINCT root FROM plugins WHERE plugin=?", {}, $options{require})};
}

my %seen; # in case multiple dbs have the same root
my $pluginq;
if (defined $options{plugin}) {
    if ($options{plugin} =~ /["\n!']/) { die "skipping suspect query: $options{plugin}" }
    $pluginq = "plugin='$options{plugin}'"
}
elsif (defined $options{theme}) {
    if ($options{theme} =~ /["\n!']/) { die "skipping suspect query: $options{theme}" }
    $pluginq = "theme='$options{theme}'"
}
else {
    $pluginq = '1=1'
}
for (@{$dbh->selectall_arrayref("SELECT DISTINCT user,db,root FROM plugins WHERE $pluginq $options{where}")}) {
    my ($user, $db, $root) = @$_;
    next if $seen{$root}++;
    next if $options{skipsuspended} && -f "/var/cpanel/suspended/$user";
    next if $options{skip} && exists $skiproots{$root};
    next if $options{require} && !exists $requireroots{$root};
    next if $options{noretry} && attempted($root);
    next if defined($options{followup}) && !followup($root, $options{followup});

    # paranoia
    if ($root =~ /["\n!]/) { warn "skipping suspect docroot: $root"; next }

    chdir $root or do { warn "not able to cd to $root -- skipping upgrade"; next };
    upgrade($user, $db, $root, $options{plugin}) if defined($options{plugin});
    upgrade_theme($user, $db, $root, $options{theme}) if defined($options{theme});
    wpupgrade($user, $db, $root) if defined($options{core});
}

sub backupfile {
    my ($user, $db) = @_;
    my $name = "/home/$user/$db.$now.sql";
    return $name if -d "/home/$user/";
    my @pwent = getpwnam($user);
    return $name unless @pwent; # will fail to open for writing
    return $pwent[7]."/$db.$now.sql";
}

sub backup {
    my ($user, $db) = @_;
    my $name = backupfile($user, $db);
    return 1 if -f $name; # we've got a duplicate upgrade somehow
    open my $f, '>', $name or do {
        warn "Failed to open $name for writing : $!";
        return 0;
    };
    chmod 0600, $name or do {
        warn "Failed to chmod 0600 $name : $!";
        close $f;
        unlink $name;
        return 0;
    };
    open my $dump, '-|', 'mysqldump', $db or do {
        warn "Failed to mysqldump $db for $user : $!";
        close $f;
        unlink $name;
        return 0;
    };
    while (defined(my $line = <$dump>)) {
        print {$f} $line;
    }
    close $dump;
    close $f;
    system gzip => $name;
    print "Backup: $name.gz\n";
    return 1
}

sub upgrade {
    my ($user, $db, $root, $plugin) = @_;
    my $shell = "su - $user -s /bin/bash -c";
    my $wpcli = qq{/usr/local/bin/wp --path="$root"};
    if (-x $cphp74) { $wpcli = "$cphp74 $wpcli" }
    elsif (-x $cphp72) { $wpcli = "$cphp72 $wpcli" }

    logattempt($root) if $options{campaign} eq "AUTOWP";
    print qq{$shell "$wpcli plugin status $plugin $skip|grep Version:"}, "\n" if defined $options{verbose};
    chomp(my $pre = qx{$shell "$wpcli plugin status $plugin $skip|grep Version:"});
    if (!defined($options{install}) && $pre !~ /\(Update available\)/) {
        print "WP-MASS-UPGRADE UNABLE $user $root $pre\n";
        if (defined $options{version}) {
            $misses++ unless $pre =~ /\b\Q$options{version}\E\b/;
        }
        return;
    }
    unless ($options{skipbackup}) {
        backup($user, $db) or do {
            warn "Failed to back up $db for $root -- skipping upgrade\n";
            $misses++;
            return;
        };
    }

    logattempt($root) unless $options{campaign} eq "AUTOWP";
    if (defined $options{install}) {
        print qq{$shell "$wpcli plugin install $options{install} $force $skip"}, "\n" if defined $options{verbose};
        system qq{$shell "$wpcli plugin install $options{install} $force $skip"};
    } else {
        print qq{$shell "$wpcli plugin update $plugin $version $force $skip"}, "\n" if defined $options{verbose};
        system qq{$shell "$wpcli plugin update $plugin $version $force $skip"};
    }
    print qq{$shell "$wpcli plugin status $plugin $skip|grep Version:"}, "\n" if defined $options{verbose};
    chomp(my $post = qx{$shell "$wpcli plugin status $plugin $skip|grep Version:"});
    print "WP-MASS-UPGRADE $user $root $pre $post\n";
    if (defined $options{version}) {
        if ($post =~ /\b\Q$options{version}\E\b/) {
            $upgrades++;
            push @users, $user;
        } else {
            $misses++;
        }
    }
}

sub wpupgrade {
    my ($user, $db, $root) = @_;
    my $shell = "su - $user -s /bin/bash -c";
    my $wpcli = qq{/usr/local/bin/wp --path="$root"};
    if (-x $cphp74) { $wpcli = "$cphp74 $wpcli" }
    elsif (-x $cphp72) { $wpcli = "$cphp72 $wpcli" }

    unless ($options{skipbackup}) {
        backup($user, $db) or do {
            warn "Failed to back up $db for $root -- skipping upgrade\n";
            $misses++;
            return;
        };
    }

    logattempt($root);
    print qq{$shell "$wpcli core update $version $force $skip"}, "\n" if defined $options{verbose};
    chomp(my $res = qx{$shell "$wpcli core update $version $force $skip"});
    print $res, "\n";
    if ($res =~ /updated successfully|is at the latest|is up to date/) {
        $upgrades++;
        push @users, $user;
    } else {
        $misses++;
    }
}

sub upgrade_theme {
    my ($user, $db, $root, $theme) = @_;
    my $shell = "su - $user -s /bin/bash -c";
    my $wpcli = qq{/usr/local/bin/wp --path="$root"};
    if (-x $cphp74) { $wpcli = "$cphp74 $wpcli" }
    elsif (-x $cphp72) { $wpcli = "$cphp72 $wpcli" }

    print qq{$shell "$wpcli theme status $theme $skip|grep Version:"}, "\n" if defined $options{verbose};
    chomp(my $pre = qx{$shell "$wpcli theme status $theme $skip|grep Version:"});
    if (!defined($options{install}) && $pre !~ /\(Update available\)/) {
        print "WP-MASS-UPGRADE UNABLE $user $root $pre\n";
        if (defined $options{version}) {
            $misses++ unless $pre =~ /\b\Q$options{version}\E\b/;
        }
        return;
    }
    unless ($options{skipbackup}) {
        backup($user, $db) or do {
            warn "Failed to back up $db for $root -- skipping upgrade\n";
            $misses++;
            return;
        };
    }

    logattempt($root);
    if (defined $options{install}) {
        print qq{$shell "$wpcli theme install $options{install} $force $skip"}, "\n" if defined $options{verbose};
        system qq{$shell "$wpcli theme install $options{install} $force $skip"};
    } else {
        print qq{$shell "$wpcli theme update $theme $version $force $skip"}, "\n" if defined $options{verbose};
        system qq{$shell "$wpcli theme update $theme $version $force $skip"};
    }
    print qq{$shell "$wpcli plugin status $theme $skip|grep Version:"}, "\n" if defined $options{verbose};
    chomp(my $post = qx{$shell "$wpcli theme status $theme $skip|grep Version:"});
    print "WP-MASS-UPGRADE $user $root $pre $post\n";
    if (defined $options{version}) {
        if ($post =~ /\b\Q$options{version}\E\b/) {
            $upgrades++;
            push @users, $user;
        } else {
            $misses++;
        }
    }
}

$options{plugin} = "WPCORE" if defined $options{core};
$options{plugin} = $options{theme} if defined $options{theme};
if ($upgrades || $misses) {
    openlog 'PluginUpgrades', '', 'LOG_USER';
    print "WP-MASS-UPGRADE SYSLOG $options{plugin} with $upgrades upgrades, $misses misses\n";
    syslog 'notice', "$options{plugin} with $upgrades upgrades, $misses misses";
    my $ua = LWP::UserAgent->new;
    $ua->agent('wpmassupgrade');
    $ua->ssl_opts(verify_hostname => 0);
    $ua->timeout(10);
    my $res = $ua->post("https://reports.soc.newfold.com/report/wp-mass-upgrade?key=$statuskey&host=$hostname&campaign=$options{campaign}&plugin=$options{plugin}&version=$version&upgrades=$upgrades&misses=$misses", Content => fake_json_encode(\@users));
    warn "[!] failed to report upgrade results to okd: ".$res->status_line unless $res->is_success;
}

# avoid another dependency for now. Works for bare usernames only.
sub fake_json_encode {
    my ($users) = @_;
    return "[".join(', ', map { qq("$_") } @$users)."]";
}
