#!/usr/local/bin/perl

use WWW::Mechanize;

use constant USERNAME => 'rsoderberg';
use constant PASSWORD => 'cFL_orkut';

use constant FETCH_CONTENT => 0;
use constant DATA_ORKUT => '/etc/mail/filster/data/orkut';
use constant USERS_ORKUT => '/etc/mail/filster/users/orkut';
use constant PARSE_CONTENT => 0;

my $args = join ' ', @ARGV;
my $agent = WWW::Mechanize->new( );

my $content; if (&FETCH_CONTENT || $args =~ /fetch_content/) {
    $agent->get('http://www.orkut.com/Friends.aspx');
    my $timeout; while ($agent->content =~ /PwdForgot.aspx/) {
	if (++$timeout > 1) { $timeout = -1; last }
	$agent->set_fields(
	    u   =>	&USERNAME,
	    p   =>	&PASSWORD,
	    Submit => 'Submit',
	);
	$agent->submit_form(
	    form_name => 'f',
	    fields => { u => &USERNAME, p => &PASSWORD },
	    button => 'Submit',
	);
    }; die "Login failed" if $agent->content =~ /PwdForgot.aspx/;

    $agent->follow_link( url_regex => qr{Friends\.aspx$} ) or die "Friends not found";

    $content = $agent->content;

    use Storable qw(lock_nstore); lock_nstore [ $content ], &DATA_ORKUT;
} else {
    use Storable qw(lock_retrieve); $content = @{ lock_retrieve &DATA_ORKUT }[0];
}

my %users; if (&PARSE_CONTENT || &FETCH_CONTENT || $args =~ /parse_content/) {
    my @content;
    $content =~ s{</td><td>}{|}g;
    @content = split /\n+/, $content;
    @content = grep { /Profile\.aspx\?uid=\d+"/ } @content;
    my %users; for my $user (@content) {
	chomp $user;
	my @user = split /\|/, $user;
	my $uid = ($user =~ /Profile\.aspx\?uid=(\d+)/)[0];
	my $email = (grep /\@[^\s]+\.[a-z]{2,4}$/, @user)[-1];
	if (length $uid && length $email) {
	    $users{$uid} = $email;
	} else {
	    warn "Data failure ($uid, $email)";
	}
    }
    use Storable qw(lock_nstore); lock_nstore \%users, &USERS_ORKUT;
} else {
    use Storable qw(lock_retrieve); %users = %{ lock_retrieve &USERS_ORKUT };
}

print join "\n", values %users;

