#!/usr/bin/env python

import sys
import os
import string
import ID3

artist = "Unknown"
title = "Unknown"

if len(sys.argv) > 1:
	filepaths = sys.argv[1:]
else:
	print "usage: id3rename mp3_file_path(s)"
	sys.exit(1)

for filepath in filepaths:
	
	if os.path.isfile(filepath):
		id3info = ID3.ID3(filepath)

		if id3info.has_key("ARTIST"):
			artist = id3info["ARTIST"].strip()
			# replace punctuation with "|", then replace "|" with ""
			artist = string.translate(artist, string.maketrans(string.punctuation, "|"*len(string.punctuation)))
			artist = string.replace(artist, "|", "")
			artist = string.replace(artist, " ", "_")

		if id3info.has_key("TITLE"):
			title = id3info["TITLE"].strip()
			# replace punctuation with "|", then replace "|" with ""
			title = string.translate(title, string.maketrans(string.punctuation, "|"*len(string.punctuation)))
			title = string.replace(title, "|", "")
			title = string.replace(title, " ", "_")

		if artist.lower() != "unknown" and title.lower() != "unknown":
			dirname = os.path.dirname(filepath)

			if len(dirname) > 0:
				dirname += os.sep

			new_filename = dirname + artist + "-" + title + ".mp3"

			if not os.path.isfile(new_filename):
				print "moving " + filepath + " to " + new_filename
				os.system("mv \"" + filepath + "\" \"" + new_filename + "\"")
			else:
				print "error: \"" + new_filename + "\" already exists!"
		else:
			missing_fields = []

			if artist.lower() == "unknown":
				missing_fields.append("artist")

			if title.lower() == "unknown":
				missing_fields.append("title")

			print "error: \"" + filepath + "\" didn't specify the following fields: " + string.join(missing_fields, ", ")
	else:
		print "error: \"" + filepath + "\" doesn't exist!"

sys.exit(0)
