#!/usr/bin/perl -w

#program designed to log in and retrieve sequences from BRCO

#REQUIRES libwww-perl-5.53 (version probably doesn't matter)
#doesn't use ssl

  use LWP::UserAgent;

  use vars qw(
        $username
        $password
        $lastname
        $loginURL
        $loginDOC
        $altLink
        $browser
        $sessid
        $req
        $res
        $req2
        $res2
        $parse1
        $parse2
        $zipURL
        $ordnum
);


@ARGV or print "No input parameters, proceeding with default.\n";

my @arg_pairs = split (/\-/, (join ' ', @ARGV));
my %args=();
foreach (@arg_pairs){
    $_ or next;
    my ($flag, $val)=split /\s+/;
    $args{$flag}=$val;
}

$ordnum=$args{'o'};
$username=$args{'u'};
$password=$args{'p'};

$ordnum or die "No order number specified, please indicate one with the -o flag\n";
$username ||= 'cl295@cornell.edu';
$password ||= 'coffee'; 
$lastname='lin'; #need to know this to construct url for ZIP file name
$loginURL='http://www.brc.cornell.edu/user/login.php';

$altLink=1;
#IMPORTANT: we have to store the large ZIP files (384 well) in filesystem because of database limitations
#we hope to have this fixed soon, but for the time being, if you are downling results from a 384 sample order, use the altLink
#actually we don't use the lastname for the altlink

$ua = LWP::UserAgent->new;

my $req = HTTP::Request->new(POST => "$loginURL");
$req->content_type('application/x-www-form-urlencoded');
$req->content("email=$username&password=$password&check=1");

my $res = $ua->request($req)->as_string;

@parse1= split (/PHPSESSID=/,$res);

@parse2= split (/\n/,$parse1[1]);
$sessid = $parse2[0];
print "$parse2[0]\n";

if ($altLink) {
        $zipURL="http://www.brc.cornell.edu/user/download/$ordnum.zip";
} else {
        $zipURL="http://www.brc.cornell.edu/user/res_zipdl.php3/"."$lastname"."_"."$ordnum.zip?sample="."$ordnum"."&PHPSESSID="."$sessid";
}

print "$zipURL\n";
my $req2 = HTTP::Request->new(GET => $zipURL);

$res2 = $ua->request($req2, "$lastname"."_"."$ordnum".".zip");

if ($res2->is_success) {
        print "ok\n";
} else {
        print $res->status_line, "\n";
}
