#!/usr/local/bin/perl

use WWW::Mechanize;

use constant OPTIONS => {
    username	=> 'rsoderberg',
    password	=> 'cFL_orkut',

    fetch	=> 0,
    data_orkut	=> '/etc/mail/filster/data/orkut',
    users_orkut	=> '/etc/mail/filster/users/orkut',
    parse	=> 0,
};

if (@ARGV) {
    exit 1 if &orkut(@ARGV);
    exit 0;
}

sub orkut (;%) {
    my %options = (%{OPTIONS}, @_);
    my $agent = WWW::Mechanize->new( );

    my $content = $options{content}; unless (length $content) {
	if (! -r $options{data_orkut} || $options{fetch}) {
	    $agent->get('http://www.orkut.com/Friends.aspx');
	    my $timeout; while ($agent->content =~ /PwdForgot.aspx/) {
		if (++$timeout > 1) { $timeout = -1; last }
		$agent->submit_form(
		    form_name => 'f',
		    fields => { u => $options{username}, p => $options{password} },
		    button => 'Submit',
		);
	    }; die "Login failed" if $agent->content =~ /PwdForgot.aspx/;

	    $agent->follow_link(text => "Friends", n => "1") or die "Friends not found";

	    $content = $agent->content;

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

    my %users; if (! -r $options{users_orkut} || $options{parse} || $options{fetch}) {
	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{$email} = $uid;
	    } else {
		warn "Data failure ($uid, $email)";
	    }
	}
	use Storable qw(lock_nstore); lock_nstore \%users, $options{users_orkut};
    } else {
	use Storable qw(lock_retrieve); %users = %{ lock_retrieve $options{users_orkut} };
    }

    return $users{$ARGV[0]};
}

