#!/usr/bin/perl -w
use strict;

use DBI;
use vars qw($DBH);
use LWP::UserAgent;
#change these to match your db
my ($db_name, $db_user, $db_pass)=(qw(name user pass));
$DBH ||=DBI->connect("dbi:mysql:$db_name","$db_user","$db_pass");
my $select ="SELECT artist_name, artist_id, wikipedia, birthyear from music_artists order by artist_name asc";
my $sth=$DBH->prepare($select);
$sth->execute || print "Couldn't execute $select";
my (@composers);
while (my @row=$sth->fetchrow_array) {
    my ($artist_name,$artist_id,$wikipedia,$db_birthyear)=($row[0],$row[1],$row[2],$row[3]);
	print $artist_name,": ",$artist_id;
	#my artists are listed last, first; wikipedia listings are first_last
    my @arts=split ', ', $artist_name; 
	my $artist_name1=$arts[1].' '.$arts[0];
    $artist_name1 =~ s/\s/_/g;
    $artist_name1 =~ s/^_//;
    my $wikipedia_url="http://en.wikipedia.org/wiki/$artist_name1";
    my ($url,$birthyear,$deathyear)=&lookup($wikipedia_url);
    if (($url ne "0") && ($birthyear != 0)) {
    	my $update = sprintf(qq!update music_artists set wikipedia="%s", birthyear="%s", deathyear="%s" where artist_id="%s"!, $artist_name1, $birthyear, $deathyear, $artist_id);
		my $st_update=$DBH->prepare($update);
		$st_update->execute || print "Couldn't execute $update";
    	print "$update \n";
   	} else {
   		print "NO INFO for $artist_name\n";
   	}
}

sub lookup {
	my $wikipedia_url=shift;
	my $ua=LWP::UserAgent->new;
	my $response = $ua->get("$wikipedia_url");
	if ($response->is_success) {
		print "Got entry";
		my $content = $response->content;
		$content =~ m/\(.*(\d{4}).*–.*(\d{4}).*\)/m;
		if ($2) { 	
			print "($1 - $2)";
			return ($wikipedia_url,$1,$2); 
		} else {
			$content =~ m/\(.*(\d{4}).*\)/m;
			print "(b. $1)";
			return ($wikipedia_url,$1,'');
			}
       } else {
            print $response->status_line;
            return(0,0,0);
        }
}
