#!/usr/bin/perl -w

use strict;

my $user = 'MY USERNAME';
my $pass = 'MY PASSWORD';

while(defined($ARGV[0]) && defined($ARGV[1]) && defined($ARGV[2])) {
    my $url = shift(@ARGV);
    my $artist = shift(@ARGV);
    my $title = shift(@ARGV);

    $url =~ s/&feature=related$//;

    my $ret = system("youtube-dl.py -u $user -p $pass -b '$url'");
    if($? == -1 || ($? & 127) || ($? >> 8)) {
        $ret = system("youtube-dl.py -u $user -p $pass '$url'");
    }
    die("Failed to execute youtube-dl.py: $!") if($? == -1);
    die("youtube-dl.py died with signal".($? & 127)) if($? & 127);
    die("Failed to download") if($? >> 8 != 0);

    my $filename;
    if($url =~ /watch\?v=(.*$)$/) {
        $filename = $1;
    } else {
        $filename = $url;
    }

    my (@cmd);
    if(-f "$filename.mp4") {
        @cmd = ('ffmpeg', '-i', $filename.'.mp4', '-vn', '-acodec', 'copy');
        push(@cmd, ('-title', $title)) if(defined($title));
        push(@cmd, ('-author', $artist)) if(defined($artist));

        my $fn;
        if(defined($title) && defined($artist)) {
            $fn = "($artist) $title.m4a";
        } else {
            $fn = $filename.'.m4a';
        }
        unlink($fn);
        push(@cmd, $fn);
    } elsif(-f "$filename.flv") {
        @cmd = ('ffmpeg', '-i', $filename.'.flv', '-vn', '-acodec', 'pcm_s16le', '-ar', '44100', $filename.'.wav');
    } else {
        die("File didn't get saved");
    }

    $ret = system(@cmd);
    die("Failed to execute ffmpeg: $!") if($? == -1);
    die("ffmpeg died with signal".($? & 127)) if($? & 127);
    die("Failed to convert to wave") if($? >> 8 != 0);

    if(-f "$filename.wav") {
        unlink($filename.'.flv');

        my @cmd = ('lame', '--preset', 'standard', $filename.'.wav');
        push(@cmd, '--tt', $title) if(defined($title));
        push(@cmd, '--ta', $artist) if(defined($artist));

        my $fn;
        if(defined($title) && defined($artist)) {
            $fn = "($artist) $title.mp3";
        } else {
            $fn = $filename.'.mp3';
        }
        unlink($fn);
        push(@cmd, $fn);

        $ret = system(@cmd);
        die("Failed to execute lame: $!") if($? == -1);
        die("lame died with signal".($? & 127)) if($? & 127);
        die("Failed to convert to mp3") if($? >> 8 != 0);

        unlink("$filename.wav");
    } else {
        unlink($filename.'.mp4');
    }
}
