#!/usr/bin/perl
#            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#                    Version 2, December 2004
#
# Copyright (C) 2004 Sam Hocevar
#  14 rue de Plaisance, 75014 Paris, France
# Everyone is permitted to copy and distribute verbatim or modified
# copies of this license document, and changing it is allowed as long
# as the name is changed.
#
#            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
#  0. You just DO WHAT THE FUCK YOU WANT TO.
#
#  This program is free software. It comes without any warranty, to
#  the extent permitted by applicable law. You can redistribute it
#  and/or modify it under the terms of the Do What The Fuck You Want
#  To Public License, Version 2, as published by Sam Hocevar. See
#  http://sam.zoy.org/wtfpl/COPYING for more details. 
#
#	lyrics fetcher for moc (http://moc.daper.net)
#
use strict;
use warnings;
use Getopt::Long;
use URI::Escape;
use HTML::Entities ();
Getopt::Long::Configure ("bundling", "gnu_compat");

my $baseurl= "http://www.lyricstime.com/search/?q=";
my $lyricstime = "http://www.lyricstime.com";
my $home = $ENV{"HOME"} || die "couldn't determine your home directory..." ;
my $pidfile = $home . "/.moc/pid";
my $title = "";
my $artist = "";
my $album = "";
my $file = "";
my @lyrics;
my @urls;
my $all;
my $writetofile;
my $help;
my $force;
my $replace;
my $lyrcounter=0;
my $printcount;
my $artistonly;
my $titleonly;
my $feat;

sub checkplaying {
	return 0 unless (-e $pidfile);
	return 1;
}
GetOptions("all|a" => \$all,
	"force|f" => \$force,
	"writetofile|w" => \$writetofile,
	"replace-umlauts|r" => \$replace,
	"num|n=s"	=> \$printcount, 
	"artistonly|t" => \$artistonly,
	"titleonly|l" => \$titleonly,
	"nofeat|e" => \$feat,
	"help|h" => \$help
) or die "Invalid command line: $!";
if($help){
	print "Usage: $0 [-wa]
	-a, --all\t\tShow all lyrics.
	-w, --writetofile\tSave lyrics to a file in the same directory as the currently played song
	-f, --force\t\tOverwrite existing files (even if no lyrics were found!)
	-r, --replace-umlauts\tReplace ö with o, ä with a etc....
	-n, --num NUM\t\tprint only lyrics number NUM
	-e, --feat\t\tDo not include featuring artists in the search (just removes everything that follows feat. or featuring)
	-t, --artistonly\tOnly use the artist as search term
	-l, --titleonly\tJust search for the title
	-h, --help\t\tHelp...\n";
	exit 0;
}

checkplaying() or die "mocp isn't running...";
my $count = 0;
-e $_ . "/curl" && $count++  foreach(split ":", $ENV{PATH});
die "curl not found" unless $count;
my @songinfo = `mocp -i`;

foreach my $line(@songinfo){
	chomp $line;
	if($line =~ m#^File: #){
		$file = $line;
		$file =~ s#^File: ##;
		if ($file !~ m#^.+\..+$#){
			print "Warning: No extension found!\n";
			$writetofile = 0;
		}
		$file =~ s#\.[^.]+$##;
		next;
	}
	if(! $replace){
		$line =~ s#ö|Ö#%F6#g;
		$line =~ s#ä|Ä#%E4#g;
		$line =~ s#ü|Ü#%FC#g;
	}
	if($replace){
		$line =~ s#ö|Ö#o#g;
		$line =~ s#ä|Ä#a#g;
		$line =~ s#ü|Ü#u#g;
	}

	$line =~ s#\s+#+#g;
	#$line =~ s#%20#+#g;
	if($line =~ m#^SongTitle#){
		$title = $line;
		$title =~ s#^SongTitle:##;
		$title= uri_escape $title, "^%A-Za-z0-9+";
		$title =~ s#%2B#+#g;
	}
	if($line =~ m#^Artist#){
		$artist = $line;
		$artist =~ s#^Artist:##;
		$artist = uri_escape $artist,  "^A-Za-z0-9%+" ;
		$artist =~ s#%2B#+#g;
	}
	if($line =~ m#^Album#){
		$album = $line;
		$album =~ s#^Album:##;
		$album = uri_escape $album, "^A-Za-z0-9%+";
		$album =~ s#%2B#+#g;
	}
}
if ($writetofile){
	if( -e $file && !$force){
		print "File $file already exists, disabling -w!\n" .
		"You can override this behaviour by adding -f to your command line.\n";
		$writetofile = 0;
	}else{
		unlink $file if (-e $file);
	}
}
my $request = $baseurl;

if ($artist && ! $titleonly){
	$artist =~ s#(feat.|featuring).*##i if ($feat);
	$request .= $artist;
}
if ($title && ! $artistonly){
	$title =~ s#(feat.|featuring).*##i if ($feat);
	$request .= $title;
}
$request .= "&t=default";
print "Request: $request\n\n";
my $html_source = `curl -s \'$request\'`;
$html_source =~ s#\r\n#\n#g;
my @results = split /\n/, $html_source;
my $bool = 0;
foreach(@results){
	if (/Matching Songs/){
		$bool = 1;
		next;
	}
	$bool = 0 if(/main content end/);
	next unless($bool);
	next unless(/<li><a href="/);
	my $url = $_;
	$url =~ s#.*href="([^"]+)".*#$1#;
	$url = $lyricstime . $url;
	push @urls, $url;

}
if (@urls == 0){
	print "No lyrics found!\n";
	exit 1;
}

foreach my $line(@urls){
	$lyrcounter++;
	next if($printcount && $lyrcounter != $printcount);
	print "###################### $lyrcounter #############################\n" unless ($writetofile);
	print "Fetching $line\n\n" unless ($writetofile);
	my $tmp = `curl -s \'$line\'`;
	#ugly, ugly, ugly....
	$tmp =~ s#\r##gxs;
	$tmp =~ s#^.*<div\s+id="songlyrics"\s*>##gxs;
	$tmp =~ s#</div>.*##gxs;
	$tmp =~ s#<br\s*/>##gxs;
	$tmp =~ s#</?p>##gxs;
	$tmp =~ s#\n{2,}#\n#gxs;
	$tmp = HTML::Entities::decode($tmp);
	if($writetofile){
		open my $outfile, ">>", $file or die "Couldn't open $file: $!";
		print $outfile $tmp;
		close $outfile;
	}
	else{
		print "$tmp\n";
	}
	exit 0 unless ($all);
}
