perl << 'EOF'
use strict;
use warnings;

use LWP::UserAgent;
use HTTP::Request;

my $ban_url            = 'url_placeholder';
my $source_host_ip     = qx{hostname -i};
my $cache_backend_conf = '/etc/apache2/conf.d/includes/balancer_backend_http.conf';
my ( @servers, @errors, @success, @notcached );

my @url_parts   = split( /\//, $ban_url );
my $host        = $url_parts[0];
my $base_domain = $host =~ s/^www\.//ir;
my $max_array   = scalar @url_parts - 1;

if ( !domain_check($base_domain) ) {
    print "[!] ERROR: $base_domain doesn't exist in the server config\n";
    exit 0;
}

caching_backends();

foreach my $server (@servers) {
    my $uri;
    if ( scalar( @url_parts > 1 ) ) {
        $uri = join( '/', @url_parts[ 1 .. $max_array ] );
    }
    else {
        $uri = '*';
    }

    my $plain = purge( $host, "http://$server:6081/$uri" );
    my $tls   = purge( $host, "https://$server:8443/$uri" );

    # 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 ) {
        print "[*] Successfully cleared the cache for http(s)://$host on $server\n";
    }
    elsif ($plain) {
        print "[*] Successfully cleared the cache for http://$host on $server\n";
    }
    elsif ($tls) {
        print "[!] ERROR: There was a problem clearing the cache for http://$host on $server. We didn't get a 204 response. It's possible this site is not behind caching.\n";
    }
    else {
        print "[!] ERROR: There was a problem clearing the cache for http(s)://$host on $server. We didn't get a 204 response. It's possible this site is not behind caching.\n";
    }
}

sub domain_check {
    my $domain = shift;
    my $file   = '/etc/userdomains';
    return 0 if ( !-s $file );
    open my $fh, '<', $file or return;
    while ( defined( my $line = <$fh> ) ) {
        return $1 if $line =~ /^\Q$domain\E: (\w+)$/;
    }
    return 0;
}

sub caching_backends {
    if ( -f "$cache_backend_conf" ) {
        open( my $fh, '<', $cache_backend_conf );
        while ( my $line = <$fh> ) {
            chomp $line;
            while (
                $line =~ m{((?:
            (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
            (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
            (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
            (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
          ))
    }gx
              )
            {
                push @servers, $1;
            }
        }
    }
}

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

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

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

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

    return $data->code =~ /^204$/;
}
EOF
