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

sub usage {
    my ($prefix) = @_;
    $prefix .= "\n" if defined $prefix;
    $prefix = "" unless defined $prefix;
    die "${prefix}usage: $0 [FLAGS] --campaign=CAMPAIGN --plugin=PLUGIN --version=VERSION [--where=WHERE]
or...: $0 [FLAGS] --campaign=CAMPAIGN --core --minor [--where=WHERE]
or...: $0 [FLAGS] --campaign=CAMPAIGN --core --minor [--where=WHERE]
or...: $0 [--chance=N] [--report] --campaign=CAMPAIGN --wpcli-user=USER --wpcli-path=ROOT --wpcli-command=COMMAND

FLAGS
  --premium          # don't add --skip-plugins to wp-cli command
  --skip-suspended
  --skip-backup
  --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
  --report           # collect wp-cli output and send to SOC Dashboard
  --dry-run          # echo commands instead of run them

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

  --wpcli-user=USER --wpcli-path=ROOT --wpcli-command=COMMAND
  --sudo-user=USER --sudo-path=ROOT --sudo-command=COMMAND
    # run specific COMMAND as USER for wordpress at ROOT
    # most other flags are incompatible

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 $appendkey = '4zJ9XMA4z)CE|aLd';
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;
my @report;
sub logw {
    push @report, $_[0] if defined $options{report};
    print $_[0];
}
@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},
    "install=s" => \$options{install},
    "chance=s" => \$options{chance},
    "noretry" => \$options{noretry},
    "followup=s" => \$options{followup},
    "theme=s" => \$options{theme},
    "dry-run" => \$options{dryrun},
    "report" => \$options{report},

    "wpcli-user=s" => \$options{wpcli_user},
    "wpcli-path=s" => \$options{wpcli_path},
    "wpcli-command=s" => \$options{wpcli_command},
    "sudo-user=s" => \$options{sudo_user},
    "sudo-path=s" => \$options{sudo_path},
    "sudo-command=s" => \$options{sudo_command},
) or usage("failed to parse opts");
if (defined $options{chance}) {
    my $n = $options{chance};
    usage("bad chance") unless $n =~ /^\d+$/ && $n >= 0 && $n <= 100;
    exit unless rand(100) < $n;
}
usage("--report without --campaign") if defined($options{report}) && !defined($options{campaign});
if (defined($options{wpcli_user}) || defined($options{wpcli_path}) || defined($options{wpcli_command})) {
    usage("--wpcli-* flags must all be given if any are given") unless defined($options{wpcli_user}) && defined($options{wpcli_path}) && defined($options{wpcli_command});
    for my $opt (grep { defined $options{$_} } keys %options) {
        next if $opt =~ /^wpcli_(?:user|path|command)$/;
        next if $opt =~ /^(?:chance|report|campaign|dryrun)$/;
        usage("flag --$opt is incompatible with --wpcli-*");
    }
    chdir $options{wpcli_path} or die "can't chdir to $options{wpcli_path} : $!";
    su_wp($options{wpcli_user}, $options{wpcli_path}, $options{wpcli_command});
    exit;
}
if (defined($options{sudo_user}) || defined($options{sudo_path}) || defined($options{sudo_command})) {
    usage("--sudo-* flags must all be given if any are given") unless defined($options{sudo_user}) && defined($options{sudo_path}) && defined($options{sudo_command});
    for my $opt (grep { defined $options{$_} } keys %options) {
        next if $opt =~ /^sudo_(?:user|path|command)$/;
        next if $opt =~ /^(?:chance|report|campaign|dryrun)$/;
        usage("flag --$opt is incompatible with --sudo-*");
    }
    chdir $options{sudo_path} or die "can't chdir to $options{sudo_path} : $!";
    su_do($options{sudo_user}, $options{sudo_path}, $options{sudo_command});
    exit;
}
usage("--campaign required or invalid") unless defined $options{campaign} && $options{campaign} =~ /^[\w-]+$/
    && (defined($options{plugin}) || defined($options{core}) || defined($options{theme}));
usage("can't do --plugin and --core at the same time") if defined($options{plugin}) && defined($options{core}); # one or the other
usage("can't do --theme and --core at the same time") if defined($options{theme}) && defined($options{core});
usage("can't do --plugin and --theme at the same time") 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("one of --version, --minor, --patch required") unless defined $version;
my $skip = "--skip-plugins --skip-themes";
$skip = "--skip-themes" if defined $options{premium};

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 (defined $options{report} && defined($options{campaign}) && @report) {
        my $ua = LWP::UserAgent->new;
        $ua->agent('wpmassupgrade');
        $ua->ssl_opts(verify_hostname => 0);
        $ua->timeout(10);
        my $reportName = $options{campaign}.".wpmass";
        my $res = $ua->post("https://reports.soc.newfold.com/report/fileappend/$reportName?key=$appendkey",
            Content => join("\n", map { s/^/$hostname /gm; $_ } @report));
        logw "[!] failed to send report to okd: ".$res->status_line."\n" unless $res->is_success;
    }
}

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 (shuffle @{$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!]/) { logw "skipping suspect docroot: $root\n"; next }

    chdir $root or do { logw "not able to cd to $root -- skipping upgrade\n"; 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 {
        logw "Failed to open $name for writing : $!\n";
        return 0;
    };
    chmod 0600, $name or do {
        logw "Failed to chmod 0600 $name : $!\n";
        close $f;
        unlink $name;
        return 0;
    };
    open my $dump, '-|', 'mysqldump', $db or do {
        logw "Failed to mysqldump $db for $user : $!\n";
        close $f;
        unlink $name;
        return 0;
    };
    while (defined(my $line = <$dump>)) {
        print {$f} $line;
    }
    close $dump;
    close $f;
    system gzip => $name;
    logw "Backup: $name.gz\n";
    return 1
}

sub su_wp {
    my ($user, $root, $cmd) = @_;
    my $wpcli = qq{/usr/local/bin/wp --path="$root"};
    if (-x $cphp74) { $wpcli = "$cphp74 $wpcli" }
    elsif (-x $cphp72) { $wpcli = "$cphp72 $wpcli" }
    return su_do($user, $root, "$wpcli $cmd")
}

sub su_do {
    my ($user, $root, $cmd) = @_;
    my $su = "/usr/bin/su";
    $su = "/bin/su" if -e "/bin/su";
    my @shell = ($su, '-', $user, '-s', '/bin/bash', '-c');
    logw "CMD: ".join(' ', @shell, qq{"$cmd"})."\n";

    chdir $root or do {
        logw "Failed to chdir to $root, skipping command for $user : $cmd\n";
        return;
    };
    $cmd = "/bin/echo $cmd" if defined $options{dryrun};
    open my $p, '-|', @shell, "$cmd" or do {
	    logw "Failed to exec $cmd : $@\n";
	    return;
    };
    local $/ = undef;
    my @out = <$p>;
    close $p;
    chomp @out;
    push @report, @out if defined $options{report};
    print "$_\n" for @out;
    return @out;
}

sub upgrade {
    my ($user, $db, $root, $plugin) = @_;
    logattempt($root) if $options{campaign} eq "AUTOWP";
    my ($pre) = grep { /Version:/ } su_wp($user, $root, "plugin status $plugin $skip");
    $pre = "" unless defined $pre;
    if (!defined($options{install}) && $pre !~ /\(Update available\)/) {
        logw "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 {
            logw "Failed to back up $db for $root -- skipping upgrade\n";
            $misses++;
            return;
        };
    }

    logattempt($root) unless $options{campaign} eq "AUTOWP";
    if (defined $options{install}) {
        su_wp($user, $root, "plugin install $options{install} $skip");
    } else {
        su_wp($user, $root, "plugin update $plugin $version $skip");
    }
    my ($post) = grep { /Version:/ } su_wp($user, $root, "plugin status $plugin $skip");
    $post = "" unless defined $pre;
    logw "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) = @_;
    unless ($options{skipbackup}) {
        backup($user, $db) or do {
            logw "Failed to back up $db for $root -- skipping upgrade\n";
            $misses++;
            return;
        };
    }

    logattempt($root);
    my $res = join "\n", su_wp($user, $root, "core update $version $skip");
    logw $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 ($pre) = grep { /Version:/ } su_wp($user, $root, "theme status $theme $skip");
    $pre = "" unless defined $pre;
    if (!defined($options{install}) && $pre !~ /\(Update available\)/) {
        logw "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 {
            logw "Failed to back up $db for $root -- skipping upgrade\n";
            $misses++;
            return;
        };
    }

    logattempt($root);
    if (defined $options{install}) {
        su_wp($user, $root, "theme install $options{install} $skip");
    } else {
        su_wp($user, $root, "theme update $theme $version $skip");
    }
    my ($post) = grep { /Version/ } su_wp($user, $root, "plugin status $theme $skip|grep Version:");
    $post = "" unless defined $pre;
    logw "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';
    logw "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));
    logw "[!] failed to report upgrade results to okd: ".$res->status_line."\n" 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)."]";
}
