#!/usr/bin/perl

use strict;

my ( $user, $domain, $action, $type ) = @ARGV;
my ( %domains, %users );

system("mkdir -p /opt/eig_linux/var/blockbots") if not -d "/opt/eig_linux/var/blockbots";

usage() unless (
	($user) &&
	($domain) &&
	($action =~ /^(enable|disable)$/) &&
	($type =~ /^(all|yahoo|bing|google|other)$/)
);

print "[*] Processing...\n";
verify_user_and_domain();

if ($action eq 'enable') {
	enable();
} else {
	disable();
}

system('/root/bin/rebuild_blockbots_include');
print "[*] Complete!\n";


############## SUBS #############
sub enable {
	my @domains;
	if ($domain eq 'all') {
		print "[*] Removing all '$type' blocks for user $user.\n";
		open my $FH, '<', '/etc/userdomains' or die "[!] Could not open /etc/userdomains\n";
		while (<$FH>) {
			my ($d, $u) = split /:\s/, $_;
			if ($u == $user) {
				push @domains, $d;
			}
		}
		close $FH;

		# Remove all blocks for each domain on the user.
		foreach my $dom (@domains) {
			remove_block($dom, $type);
		}
		
		# Don't forget to remove the block for the user as well
		remove_block($user, $type);
	} else {
		print "[*] Removing blocks for $domain.\n";
		remove_block($domain, $type);
	}
}

sub disable {
	if (-f "/opt/eig_linux/var/blockbots/$user.$type" || -f "/opt/eig_linux/var/blockbots/$user.all") {
		die "[!] $user already has '$type' bots blocked.\n";
	}

	if (-f "/opt/eig_linux/var/blockbots/$domain.$type" || -f "/opt/eig_linux/var/blockbots/$domain.all") {
		die "[!] $domain already has '$type' blocked.\n";
	}

	if ($domain eq 'all') {
		add_block($user, $type);
	} else {
		add_block($domain, $type);
	}
}

# Make sure the user exists.
sub verify_user_and_domain {
	my $found = 0;
	if ( (! -f "/var/cpanel/users/$user") || (! -d (getpwnam("$user"))[7]) ) {
		die "[!] The user you provided doesn't exist or the home directory is missing.\n";
	}

	if ($domain ne 'all') {
		open my $FH, '<', '/etc/userdomains' or die "[!] Could not open /etc/userdomains\n";
		while (<$FH>) {
			$found = 1 if ($_ =~ /^$domain:\s$user$/);
		}
		close $FH;

		die "[!] The user and domain you entered don't appear to associate together.\n" if (!$found);
	}
}

# Add the file for the block.
sub add_block {
	my $file = shift;
	my $bot = shift;

	system("touch /opt/eig_linux/var/blockbots/$file.$bot");
	print "[*] Added '$file' to block '$bot' robots.\n";
}

sub remove_block {
	my $file = shift;
	my $bot = shift;

	if ($bot eq 'all') {
		unlink ("/opt/eig_linux/var/blockbots/$file.all");
		unlink ("/opt/eig_linux/var/blockbots/$file.google");
		unlink ("/opt/eig_linux/var/blockbots/$file.yahoo");
		unlink ("/opt/eig_linux/var/blockbots/$file.bing");
	} else {
		unlink ("/opt/eig_linux/var/blockbots/$file.$bot");
	}
}

sub usage() {
	print "blockbots <user> <all|domain> <disable|enable> <all|bing|google|yahoo|other>\n";
	print "The \"other\" option listed will block the following crawlers:\n";
	print "\t\t\t80legs.com , Yandex, Baidu\n";
	exit;
}
