#!/usr/bin/env python
#
# Copyright 2011 Philipp Winter (phw@7c0.org)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# -------------------
# Important aspects:
# - Make a backup of your audio data before using this script!
# - The artist/date/album/tracknumber/title tags must be present.
# - This script moves your audio data just by looking at the *tags*.
# - Only audio data is moved and no m3u/jpg/log/cue/... files
# - The new file structure is: $artist/$year - $album/$tracknumber - $title
#   However, this can be changed in the code.
# -------------------

import shutil, os, mutagen, sys


def moveFile( fileName, newRoot ):

	try:
		obj = mutagen.File(fileName, easy=True).tags
	except AttributeError, e:
		print "Skipping '%s'" % fileName
		return

	ext = fileName.split('.')[-1]
	newPath = newRoot + \
		obj['artist'][0].replace('/', '&') + '/' + \
		obj['date'][0].replace('/', '&') + ' - ' + \
		obj['album'][0].replace('/', '&') + '/'
	newName = obj['tracknumber'][0].replace('/', '-') + ' - ' + \
		obj['title'][0].replace('/', ' - ') + '.' + ext

	try:
		os.makedirs(newPath)
	except OSError:
		pass

	newName = newName.replace('/', '_')

	shutil.move(fileName, newPath + newName.strip())


if __name__ == '__main__':

	if len(sys.argv) != 3:
		print >>sys.stderr, "\nUsage: %s <oldroot> <newroot>\n" % sys.argv[0]
		sys.exit(1)
	newRoot = sys.argv[2]
	oldRoot = sys.argv[1]

	if newRoot[-1] != '/':
		newRoot = newRoot + '/'

	print "Do you have a backup for '%s'? (y/n) " % oldRoot,
	r = sys.stdin.readline().strip()
	if r == "n":
		print "\nA backup of all data is mandatory!\n"
		sys.exit(0)
	elif r == "y":
		print "\nI hope this is correct. Proceeding.\n"
	else:
		print "\nWrong input, answer with 'y' or 'n'.\n"
		sys.exit(2)

	print "Moving files from '%s' to '%s'" % (oldRoot, newRoot)

	for root, dirs, files in os.walk(oldRoot):
		for f in files:
			moveFile(root + '/' + f, newRoot)

