#!/usr/bin/env python2.4

import sys, os, string, os.path
import shutil
import eyeD3
import tempfile

#basedir = "/tmp/walkman"
basedir = "/media/WALKMAN/MUSIC"

def filterFilename(fname):
	"""Strip out characters invalid or inappropriate for a filename"""
	stripchars = ["/", "\\", "[", "]", "?"]
	for c in stripchars:
		fname = fname.replace(c, "")
	return fname

def makePath(dirname):
	dirs = []
	dirname = os.path.abspath(dirname)

	# eliminate slash from the end if found
	if os.path.split(dirname)[1] == '':
		dirname = os.path.split(dirname)[0]
	
	while dirname != "/":
		dirs.append(dirname)
		dirname = os.path.split(dirname)[0]
	
	dirs.reverse()	

	for dirname in dirs:
		#print dirname
		# check if exists, create if not
		if not os.path.exists(dirname):
			os.mkdir(dirname)

def getMP3Name(tag, isCompilation=False):
	
	has_tracknum = False
	has_cdnum = False

	if tag.getTrackNum()[0] != None:
		has_tracknum = True
	if tag.getDiscNum()[0] != None and tag.getDiscNum()[0] > 0 and tag.getDiscNum()[1] != 1:
		has_cdnum = True

	if has_tracknum:
		if has_cdnum:
			mp3_fname = "%d-%02d %s.mp3" % (
				tag.getDiscNum()[0],
				tag.getTrackNum()[0],
				filterFilename(tag.getTitle()))
		else:
			mp3_fname = "%02d %s.mp3" % (
				tag.getTrackNum()[0],
				filterFilename(tag.getTitle()))
	else:
		mp3_fname = "%s.mp3" % (
			filterFilename(tag.getTitle()))
		

	artistdir = filterFilename(tag.getArtist())

	if isCompilation:
		artistdir = "Compilations"

	out_fname = os.path.join(
		basedir,
		artistdir,
		filterFilename(tag.getAlbum()),
		mp3_fname)
	
	return out_fname

def processMP3(fname):
	if os.path.splitext(fname)[1] != ".mp3":
		return

	# copy file to temp file
	tfile = tempfile.NamedTemporaryFile()
	shutil.copyfileobj(file(fname), tfile)

	# sanitise tags and convert to v2.4
	os.system("mid3v2 -C \"%s\" >/dev/null" % tfile.name)

	# open tags from file
	tag = eyeD3.Tag()
	tag.link(tfile.name)
		
	# get output filename
	isCompilation = False
	if os.path.abspath(fname).find("Compilations") > -1:
		isCompilation = True
	outname = getMP3Name(tag, isCompilation)
		
	# alter album tag if disc number tag is present
	if tag.getDiscNum()[0] != None and tag.getDiscNum()[0] > 0 and tag.getDiscNum()[1] != 1:
		tag.setAlbum(tag.getAlbum() + (u" - Disc %d" % tag.getDiscNum()[0]))

	# add album art if available
	for covername in ("cover.jpg", "folder.jpg", "Folder.jpg", ".folder.jpg"):
		coverpath = os.path.join(os.path.split(fname)[0], covername)
		if os.path.exists(coverpath):
			print "Found cover art -- attaching"
			os.system("convert \"%s\" -scale 200x200 -quality 70 /tmp/cover.jpg" % coverpath)
			ptype = eyeD3.frames.ImageFrame.stringToPicType("FRONT_COVER")
			tag.addImage(ptype, None, None)
			tag.addImage(ptype, "/tmp/cover.jpg", u"")

	# save tag, converting to v2.3
	tag.update(eyeD3.ID3_V2_3)
		
	# make destination directory if needed
	makePath(os.path.split(outname)[0])
	
	# copy file
	print "Copying '%s' to '%s'" % (fname, outname)
	shutil.copy(tfile.name, outname)

	tfile.close()

if __name__ == "__main__":
	files_to_process = []

	for fname in sys.argv[1:]:
		if os.path.isfile(fname):
			# single file -- process it
			files_to_process.append(fname)

		elif os.path.isdir(fname):
			# folder -- walk it
			for root, dirs, files in os.walk(fname):
				for f in files:
					files_to_process.append(os.path.join(root, f))

	
	for fname in files_to_process:
		processMP3(fname)
