perl << 'EOF'
use strict;
use Sys::Hostname;
use LWP::UserAgent;
use HTTP::Request;
use JSON;
my $user = "user_placeholder";
my $server = hostname;
my (@errors, @success, @notcached);

if ( ! -f "/var/cpanel/users/$user" ){
    print "[!] User \"$user\" not found\n";
    exit(1);
}

open my $f, '<', '/etc/userdomains';
chomp ( my @domains = map { [split /: /]->[0] } grep { /: \Q$user/ } <$f> );
close $f;

sub purge {
    my ( $host, $url ) = @_;

    my $r = HTTP::Request->new( "PURGE", "$url" );
    $r->header( "Host" => "$host" );

    my $ua = LWP::UserAgent->new;
    $ua->ssl_opts(verify_hostname => 0);
    $ua->timeout(2);

    my $data = $ua->simple_request( $r );

    return $data->code =~ /^20[04]$/;
}

foreach my $domain (@domains) {
    if ( -f "/etc/cpanel/proxy_conf/$domain" ) {
        # it's cached. this overrides the .json
    } else {
        open my $f, '<', "/etc/cpanel/proxy_conf/$domain.json"
            or do { push @notcached, $domain; next };
        my $obj;
        eval { local $/ = undef; $obj = decode_json(<$f>); };
        close $f;
        if (!$obj) { push @notcached, $domain; next }
        my $cached;
        # - OWP use wordpress_caching
        # - although caching_cli.pl uses 0 and 1 values for status, portal
        #   also writes these files and a "false" (true string, not false
        #   boolean) was observed.
        eval { $cached = 1 if $obj->{caching}{status} && $obj->{caching}{status} ne 'false' };
        eval { $cached = 1 if $obj->{wordpress_caching}{status} && $obj->{wordpress_caching}{status} ne 'false' };
        if (!$cached) { push @notcached, $domain; next }
    }

    my $plain = purge( $domain, "http://127.0.0.1:8080/*" );
    my $tls = purge( $domain, "https://127.0.0.1:8443/*" );

    # indicate whether both succeeded, but in a way that deemphasizes the TLS results
    # should probably make results more explicit when TLS caching is the norm
    if ($plain && $tls) {
        push @success, $domain;
        print "[*] Successfully cleared the cache on: http(s)://$domain\n";
    } elsif ($plain) {
        push @success, $domain;
        print "[*] Successfully cleared the cache on: http://$domain\n";
    } else {
        push @errors, $domain;
    }
}

print "\n[*] Purge cache run report for $user on $server:\n\n";
print "[+] Successful domains: " . scalar(@success) . "\n";
print "[+] Uncached domains: " . scalar(@notcached) . "\n\n";

foreach my $domain (@notcached) {
    print "Not cached: $domain\n";
}

print "\n[!] Errors: " . scalar(@errors) . "\n\n";

foreach my $domain (@errors) {
    print "Errors on: $domain\n";
}
EOF
