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

# one use case: for f in ~/cds/*.flac; do mbid=`./mbz --flac $f --get-release-id`; echo $f $mbid; done;

use Getopt::Long;
use MusicBrainz;

GetOptions(
    'flac=s' =>\my $FLAC_FILE,
    'get-release-id' => \my $GET_RELEASE_ID,
    'xml' =>\my $GET_XML,
);

my $discid;

if ($FLAC_FILE) {
    require Audio::FLAC::Header;
    my $flac = Audio::FLAC::Header->new($FLAC_FILE) or die "Can't read FLAC header from $FLAC_FILE\n";
    $discid = $flac->tags('MBZ_DISCID') or die "No MBZ_DISCID tag in $FLAC_FILE\n";
} else {
    $discid = shift;
}

# make the output terminal handle UTF-8 characters
binmode STDOUT, ':utf8';

# just dump the XML, if requested
if ($GET_XML) {
    print lookup_release($discid);
    exit;
}

# otherwise, do the full parsing of the data
my $info = get_musicbrainz_info($discid);

exit unless $info;

if ($GET_RELEASE_ID) {
    print "$$info{MUSICBRAINZ_ALBUMID}\n";
} else {
    for my $key (sort keys %{ $info }) {
        print "$key=$$info{$key}\n" unless ref $info->{$key};
    }
}
