#!/usr/bin/perl

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

die("[!] ERROR: Please provide a URL to purge.\n") if ( scalar @ARGV < 1);

my $uri;
my $ban_url = $ARGV[0];
$ban_url =~ s/http(s)?:\/\///g;

my @url_parts = split(/\//, $ban_url);
my $host = $url_parts[0];
my $max_array = scalar @url_parts - 1;

if ($host !~ /\S+\.\S+/) {
        print "[!] Invalid url/domain.\n";
        return;
}

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

my $r = HTTP::Request->new( "PURGE", "http://127.0.0.1:8080/$uri" );
$r->header( "Host" => "$host" );

my $ua = LWP::UserAgent->new;
$ua->timeout( 5 );
$ua->agent( 'ESO-utils-shared/1.0 purgecache' );

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

if ($data->code =~ /^204$/) {
        print "[*] Successfully cleared the cache for $host\n";
} else {
        print "[!] ERROR: There was a problem clearing the cache for $host. We didn't get a 204 response. It's possible this site is not behind caching.\n";
}
