#!/usr/bin/env ruby
 
# Written for ruby 1.8. Not tested with later Ruby versions.
# Please note that this script only takes ARTIST - TITLE.mp3 information.
# Any other ID3 tags are DELETED.
# This script depends on the 'id3v2' app to be installed as well as the 'id3' gem.
# The need for id3v2 can be removed once tag writing support is added to the id3 gem.
 
require 'rubygems'
require 'id3'
 
DIRECTORY = "/home/ftp/music"
 
Dir.foreach( DIRECTORY ) do |file|
 
	# Skip hidden files
	if( file !~ /^\./ )
 
		# Fix uppercase file extentions
		if( file =~ /^(.+?)\.MP3$/ )
			puts "Fixing #{file} extention."
			File.rename( "#{DIRECTORY}/#{file}", "#{DIRECTORY}/#{$1}.mp3" )
		end
 
		# Remove ID3v1 tags
		if( ID3.hasID3v1tag?( "#{DIRECTORY}/#{file}" ) )
			puts "Removing ID3v1 tag for #{file} "
			ID3.removeID3v1tag( "#{DIRECTORY}/#{file}" )
		end
 
		# See if filename is parsable
		if( file !~ / {2,}/ && file =~ /^(.+?) - (.+?)\.mp3$/ )
 
			rewrite = false
 
			# Grab parsed out information
			artist = $1
			title = $2
 
			# Read ID3v2 info
			t = ID3::Tag2.new
			t.read( "#{DIRECTORY}/#{file}" )
 
			# Check and rewrite tags
			t.each do |tagname,tag|
 
				# Check artist tag
				if( tagname == "ARTIST" )
					if( tag['text'] != artist )
						puts "Updating artist for '#{file}' from '#{tag['text']}' to '#{artist}'."
						rewrite = true
					end
 
				# Check title tag
				elsif( tagname == "TITLE" )
					if( tag['text'] != title )
						puts "Updating title for '#{file}' from '#{tag['text']}' to '#{title}'."
						rewrite = true
					end
 
				# Check for obsolete tags
				elsif( tagname != "CONTENTTYPE" && tagname != "ARTIST" && tagname != "TITLE" )
                                        puts "Obsolete tag '#{tagname}' found. Deleting."
					cmd = "id3v2 -D \#{DIRECTORY}/#{file}\" >> /dev/null"
					system( cmd )
					rewrite = true
				end
			end
 
			# Write out tags if needed.
			if( rewrite )
				cmd = "id3v2 -g 12 -a \"#{artist}\" -t \"#{title}\" \"#{DIRECTORY}/#{file}\" >> /dev/null"
				system( cmd )
 
				# Instantly kill off the ID3v1 tag again.
				ID3.removeID3v1tag( "#{DIRECTORY}/#{file}" )
			end
 
		else
			puts "Could not parse '#{file}'. Not touching tags."
		end
	end
end