#!/usr/bin/perl

use strict;
use LWP::Simple;
use Data::Dumper;
use JSON;
$|=1;

die "$0 <search param>" unless $ARGV[0];
my $root_url = "http://next.lala.com/api/AutoComplete/songAutoComplete";
my $content = get "$root_url?prefix=$ARGV[0]";
my $ref = from_json($content);
my $num = 0;
foreach (@{$ref->{data}->{list}}) {
  print "$num : $_->{artist} - $_->{title}\n";
  $num++;
}
print "Download which? > ";
my $req = <STDIN>;
die "not valid" if ($req < 0 or $req > $num);
my $download_url = "http://next.lala.com/api/Player/getTrackUrls?flash=true&webSrc=lala&widgetId=LalaHeadlessPlayer&T=" . $ref->{data}->{list}->[$req]->{playToken};
my $play_url = get $download_url;
my $play_ref = from_json($play_url);
my $download_link = $play_ref->{data}->[0]->{url};
print "Getting: $download_link\n";
my $filename = $ref->{data}->{list}->[$req]->{artist} ."-" . $ref->{data}->{list}->[$req]->{title} . ".mp3";
print "Downloading to $filename\n";
system("wget -O '$filename' $download_link");
