#!/usr/bin/perl

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

# Takes either a user or a domain/uri as an argument.

die("[!] ERROR: Please provide a URL or USER to purge.\n") if ( scalar @ARGV < 1);
die("[!] ERROR: This server does not appear to be using the cache layer.\n") unless ( -f "/etc/nginx/conf.d/proxyips" );

if ( $ARGV[0] =~ /^[a-z][0-9a-z\-]{1,16}$/ ) {
        purge_user_cache($ARGV[0]);
} else {
        purge_domain_uri($ARGV[0]);
}

sub purge_domain_uri {
        my $ban_url = shift;
        my $uri;
        $ban_url =~ s/http(s)?:\/\///g;

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

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

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

        purge( $host, $uri );
}

sub purge_user_cache {
        my $user = shift;

        my @domains;
        open my $FH, '<', '/etc/userdomains';
        while (<$FH>) {
                chomp;
                if ($_ =~ /(\S+): $user$/) {
                        push @domains, $1;
                }
	}
        close $FH;

        foreach my $host (@domains) {
                purge( $host, '*' );
        }
}

sub purge {
        my $host = shift;
        my $uri = shift;

        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";
        }
}
