#!/usr/bin/perl
#
# Balaji <balaji at balajin dot net>
#
# To fetch birthday's of friends from Live Journal

use strict;
use HTTP::Lite;
use Digest::MD5 qw( md5_hex );
use Getopt::Long;

#Proxy Connection
my $proxy="";

my ($user, $pass, $today, $md);

#GetCommand line options
GetOptions(	"user=s" => \$user,
				"pass=s" => \$pass,
				"today" => \$today,
				"date:s" => \$md
			 );

die "Usage: $0 --user=<username> [--pass=<password>] [--today] [--date=<mm-dd>]\n" if !$user;

# Prompt for LJ password
if ( !$pass ) {
system("stty -echo");
print STDERR "Password: ";
$pass = <STDIN>;
system("stty echo");
chomp $pass;
print STDERR "\n";
}

# Hash password
$pass = md5_hex($pass);

my %vars = ( 
	 "mode"=>"getfriends",
	 "user"=>"$user",
	 "hpassword"=>$pass,
	 "includebdays"=>1
	);

my $http = new HTTP::Lite;
$http->proxy($proxy) if $proxy;
$http->prepare_post(\%vars);

my $req = $http->request("http://www.livejournal.com/interface/flat") or die "Unable to connect $!";

die "Request failed ($req): ".$http->status_message() if $req ne "200";

my %return = split(/\n/, $http->body());

if ( exists($return{"success"}) && ($return{"success"} == "OK") )  {
	#print $return{"success"};
	my $friendcount = $return{"friend_count"};	
	
	if ( $today ) {
		my ($mday, $mon) = (localtime)[3,4];
		$mon++;
		$today = sprintf("%02d-%02d",$mon,$mday);
		print "People celeberating Birthday on $today\n";
		print "\nUsername\t\tFull Name\t\t\tBirthday\t\n";	
		
		for (my $i=1;$i<=$friendcount; $i++) {
			if ( $return{"friend_".$i."_birthday"} =~ /$today$/ ) {
				printf "%-16s\t%-24s\t%-8s\n",$return{"friend_".$i."_user"}, $return{"friend_".$i."_name"}, $return{"friend_".$i."_birthday"} 
			}
		}
	}
	elsif ( $md ) {
      print "People celeberating Birthday on $md\n";
      print "\nUsername\t\tFull Name\t\t\tBirthday\t\n";

      for (my $i=1;$i<=$friendcount; $i++) {
         if ( $return{"friend_".$i."_birthday"} =~ /$md$/ ) {
            printf "%-16s\t%-24s\t%-8s\n",$return{"friend_".$i."_user"}, $return{"friend_".$i."_name"}, $return{"friend_".$i."_birthday"}
         }
		}
	}
	else {
		print "\nUsername\t\tFull Name\t\t\tBirthday\t\n";	
		for(my $i=1; $i<=$friendcount; $i++) {
			printf "%-16s\t%-24s\t%-8s\n",$return{"friend_".$i."_user"}, $return{"friend_".$i."_name"}, $return{"friend_".$i."_birthday"};
		}
	}
	
}
else {
		die "Server Error, try again later.\n";
}

