#!/usr/bin/perl

# make sure each mp3 file given has an ID3v2 tag

use strict;
use warnings;

use MP3::Tag;

foreach my $file (@ARGV) {
    # read MP3 info
    my $mp3 = MP3::Tag->new($file);
    next unless defined $mp3;
    $mp3->get_tags;

    # if no ID3v2 tag, create one    
    if (not exists $mp3->{ID3v2}) {
        print "Adding ID3v2 tag to $file\n";
        $mp3->new_tag('ID3v2');
        $mp3->{ID3v2}->write_tag;
    }

    # reading ID3v1 and copy if not found in ID3v2
    if (exists $mp3->{ID3v1}) {
        my $v1 = $mp3->{ID3v1};
        my $v2 = $mp3->{ID3v2};

        foreach my $frame qw(title album artist) {
            if ($v1->$frame and (not defined $v2->$frame)) {
                my $value = $v1->$frame;
                print "frame $frame not defined in ID3v2, copying value from ID3v1: $value\n";
                $v2->$frame($value);
            }
        }

        $mp3->{ID3v2}->write_tag;
    }
}