#!/usr/bin/perl

use strict;
use Perlwikipedia;

open(PW, "/home/st47/pass");
my $pass=<PW>;
close PW;
chomp($pass);

my $editor=new Perlwikipedia('Bot/WP/EN/ST47/AccReqBot');
$editor->login('AccReqBot', $pass);

my $accreq=$editor->get_text('Wikipedia:Request an account');
while ($accreq=~/
	==\s?([^=\n]+)\s?==
	[^\{]+
	\Q{{account request\E
	[^\|]+
	\Q|username\E\s?=\s?
	([^\n]+)
	[^\|]+
	\Q|e-mail address\E\s?=\s?
	([^\n]+)
	[^\}]+
	\}\}
	(.*?)
	(?=(==|$))
/sgix){ 
	my $section=$1;
	my $username=$2;
	my $email=$3;
	my $content=$4;
	print "\n$username:";
	my $exists=&does_this_exist($username, $content);
	if ($exists eq "user") {
		&created($section, $username, $email, $content);
	} elsif ($exists eq "0") {
		&old($section, $content, $username);
	}

}
print "\nDone!\n";
my $log=$editor->get_text('User:ST47/ARBLog');
$editor->edit('User:ST47/ARBLog', '*Ran at ' . '~'x5 . '\n' . $log, 'Success!');

sub does_this_exist {
	my ($username, $content) = @_;

	if ($content =~ /\Q{{ACC|c}}\E/i) {
		print " {{ACC|c}}!";
		return "user";
	}

	my $res = $editor->{mech}->get('http://en.wikipedia.org/w/index.php?title=Special:Log/newusers&page=User:' . $username);
	my $log=$res->content;

	if ($log =~ /created new account/) {
		print " created by user";
		return "user";
	}
return 0;
}

sub created {
	my ($section, $username, $email, $content) = @_;
	my $accreq=$editor->get_text('Wikipedia:Request an account');
	my $accreqo=$accreq;
	print " removing $section";
	$accreq=~s/
		==\s?\Q$section\E\s?==
		[^\{]+
		\{\{
		[^\}]+
		\}\}
		.*?
		((?=(==|$)))
	/\1/six;
	if ($accreqo eq $accreq) {print " couldn't remove!"} else {
	$editor->edit('Wikipedia:Request an account', $accreq, "Removing $username, done.");


	my @Time=localtime;
	my $Monthn=$Time[4]+1;
	my $Month;
	if ($Monthn == 4) {$Month = "April"}
	if ($Monthn == 5) {$Month = "May"}
	if ($Monthn == 6) {$Month = "June"}
	my $Day=$Time[3];

	my $log=$editor->get_text("Wikipedia:Request an account/$Month 2007");
	unless ($log =~ /$username/) {
		$log=~s/\n{{Wikipedia:Request an account\/F/\n*{{useracc|$username}}\n{{Wikipedia:Request an account\/F/;
		$editor->edit("Wikipedia:Request an account/$Month 2007", $log, "Adding $username");
	
	my $talk = $editor -> get_text("User talk:$username");
	chomp $talk;
	$talk || $editor->edit("User talk:$username", '{' . '{sub' . 
'st:' . 'User:ST47/Welcome}} --~~' . '~~');

	}
	print " Archived";
}}


sub old {
	my ($section, $content, $username) = @_;
	if ($content =~ /
		\Q{{ACC|\E
		.+?
		\Q}}\E
		.+?
		..:..,\s(..?)\s\w+\s2007
	/ix) {
		my $day = $1;
		if (($day + 3) < (localtime[3])) {
			my $accreq=$editor->get_text('Wikipedia:Request an account');
			my $accreqo=$accreq;
			print " removing old $section";
			$accreq=~s/
				==\s?\Q$section\E\s?==
				.*?
				(==|$)
			/\1/six;
			if ($accreqo eq $accreq) {print " couldn't remove!"} else {
				$editor->edit('Wikipedia:Request an account', $accreq, "Removing $username, old.");
			}
		}
	}
}