#!/usr/bin/perl -w

use strict;
use warnings;

use Cwd;
use File::Basename;
use File::Spec;

use vars qw(@files $path $artist $year $album $trackn $title $tagfmt);

$tagfmt="ARTIST=%s\nDATE=%04.4d\nALBUM=%s\nTRACKNUMBER=%02d\nTITLE=%s\nDESCRIPTION=%s\n";

my $cwd=cwd();

if (!($path=$ARGV[0]))
{
    print "Usage: $0 FILES\n";
    exit(1);
}

my $found = "";
my $cur   = "";

if (0)
{
    $found = `find "$cwd" -type f -printf "%p\n"`;
    @files = split("\n", $found);
}
else
{
    my $i=0;
    foreach my $a (@ARGV)
    {
	if (grep(/\//, $a))	# seems like we got almost absolute path :)
	{
    	    $files[$i] = $a;
    	}
    	else			# got basename path only, join with cwd
    	{
    	    $files[$i] = $cwd."/".basename($a);
    	}
        $i++;
    }
}

foreach $cur (@files)
{
    my($fname, $dirs, $suff) = fileparse($cur, qr/\.[^.]*/);

    my @art  = split("/", $dirs);
    my $nart = @art;

    if ($nart < 2)
    {
	print "WARNING: please provide file names with al least 2 dirs in path, absolute path is better :)\ngot: '$cur'\n";
	next;
    }

    if ($suff ne ".flac")
    {
    	next;
    }


    my @ya   = split("-", $art[$nart-1], 2);
    my $nya  = @ya;
    my @tt   = split("-", $fname, 2);
    my $ntt  = @tt;
    $artist = $art[$nart-2];
    $year   = $ya[$nya-2];
    $album  = $ya[$nya-1];
    $trackn = $tt[$ntt-2];
    $title  = $tt[$ntt-1];

    my $fp;
    open($fp, ">", "/tmp/tag_album$$.tmp");
    printf $fp ($tagfmt, $artist, $year, $album, $trackn, $title, "ripped by Winex (cdparanoia, flac)");
    close($fp);

    my $out = "";
    # WARNING, haven't tested how is those options to metaflac works in order!
    #$out=`metaflac --export-tags-to="$dirs"\/"$fname".oldtags "$cur"`;
    #$out=`cat /tmp/tag_album$$.tmp | metaflac --preserve-modtime --remove-all-tags --import-tags-from=- "$cur"`;
    if (1)
    {
	$out=`cat /tmp/tag_album$$.tmp | metaflac --preserve-modtime --export-tags-to="$dirs"\/"$fname".oldtags --remove-all-tags --import-tags-from=- "$cur"`;
	`rm "$dirs/$fname.oldtags"` if ( -s "$dirs/$fname.oldtags" == 0);
    }
    else
    {
	$out=`cat /tmp/tag_album$$.tmp | metaflac --preserve-modtime --import-tags-from=- "$cur"`;
    }
    
    if ($? != 0)
    {
	print "ERROR: '$cur':\n".$out."\n";
    }
    else
    {
	print "$cur: OK\n";
    }

    unlink("/tmp/tag_album$$.tmp");
}
