#! /usr/bin/env perl

# wp core verify-checksums --allow-root 
# wp-cli.org

use warnings;
use strict;
use File::Basename;
use Cwd;

# command used to discover WordPress sites. Should return fully qualified path to a file
my $findCommand = "find /var/www/clients -path '*/web/*' -type f -name wp-config.php | grep -v private";
# regular expression to determine path, client directory and web site directory
my $sitePattern = '(.*)/([a-z0-9-]+)/([a-z0-9-]+)/web';

sub getSiteName {
   my $path = shift;
#   print STDERR "==================\n$path\n";
   return '' unless $path =~ m/$sitePattern/;
   my $basePath = $1;
   my $client = $2;
   my $site = $3;
#   print STDERR "\t$basePath\n\t$client\n\t$site\n";
   # do a long ls of the client directory, looking for the line which defines the symbolic link
   my $temp = `ls -ablph $basePath/$client | grep $site | grep /var`;
   chomp $temp;
#   print STDERR "\t$temp\n";
   # only get the symbolic link name
   if ( $temp =~ m/.*\s+([a-z0-9.-]+)\s+->/ ) {
#      print STDERR "\tReturning $temp\n";
      return $1;
   } else {
#      print STDERR "\tReturning $path\n";
      return $path;
   }
}
   

sub checkSite {
   my $sitename = shift;
   # strip off any file name
   $sitename = dirname( $sitename );
   # remember our current directory
   my $oldDir = getcwd();
   # move to the WordPress install directory
   chdir $sitename;
   # run the wp command line tool
   my $output = `wp core verify-checksums --allow-root 2>&1`;
   # go back to our old directory
   chdir $oldDir;
   # if we have success, return null, else return the output
   return $output =~ m/^success/i ? '' : &getSiteName( $sitename ) . "\n$output";
}
   
# find all wites which have wp-config in them
my @sites = `$findCommand`;
chomp @sites;
# check all of those sites
foreach my $site ( @sites ) {
   # only check if they are in the web directory
   next unless $site =~ m@client(\d+)/web(\d+)/web@;
   # Now, check the site
   if ( my $result = &checkSite( $site ) ) { # we have an error
      print "Possible Infected WordPress Site $site\n$result\n";
   }
}   
      
1;
