#!/usr/bin/python

import os,re,sys
import eyeD3

def latin1toascii(s):
	conv = { 192:'A', 193:'A', 194:'A', 195:'A', 196:'A', 197:'A', 198:'AE',
	199:'C', 200:'E', 201:'E', 202:'E', 203:'E', 204:'I', 205:'I', 206:'I',
	207:'I', 208:'D', 209:'N', 210:'O', 211:'O', 212:'O', 213:'O', 214:'O',
	215:'X', 216:'O', 217:'U', 218:'U', 219:'U', 220:'U', 221:'Y', 223:'ss',
	224:'a', 225:'a', 226:'a', 227:'a', 228:'a', 229:'a', 230:'ae', 231:'c',
	232:'e', 233:'e', 234:'e', 235:'e', 236:'i', 237:'i', 238:'i', 239:'i',
	240:'o', 241:'n', 242:'o', 243:'o', 244:'o', 245:'o', 246:'o', 248:'o',
	249:'u', 250:'u', 251:'u', 252:'u', 253:'y', }
	out=""
	for i in s:
		if ord(i) > 127:
			if ord(i) in conv:
				out+=conv[ord(i)]
			else:
				out+='_'
		else:
			out+=str(i)
	return out

def filename(s):
	conv = { ' ':'_', '&':'and', "'":"_", '"':'_', '*':'_', '.':'_', '/':'-', ':':'-', '?':'_', ',':'_', '!':'_', ';':'_'}
	out=""
	for i in s:
		if i in conv:
			out+=conv[i]
		else:
			out+=i
	while out.find('__')!=-1:
		out=out.replace('__','_')
	out=out.strip('_')
	out=out.lower()
	return out

def format(n,a,t,ext):
	fname="%02d-%s-%s"%(n,a,t)
	fname="%s.%s"%(filename(latin1toascii(fname)),ext)
	return fname

def saferename(s,d):
#	print s,d
	if os.path.exists(d):
		print "WARNING: NO overwrite",s,d
	else:
		os.rename(s,d)

def renamefile(s):
	sdir=os.path.dirname(s)
	sbase=os.path.basename(s)

	tag=eyeD3.Tag()
	tag.link(s)

	ta=tag.getArtist()
	tt=tag.getTitle()
	tn=tag.getTrackNum()[0]

	tpos=tag.frames["TPOS"]
	if tpos:
		tpost=tpos[0].text
		tn+=int(tpost)*100
	else:
		# for 101-naming
		mo=re.match("([1-9][0-9][0-9])-",sbase)
		if mo:
			tn=int(mo.group(1))

	if tn>=1 and len(ta)>1 and len(tt)>0:
		dbase=format(tn,ta,tt,"mp3")
		if dbase!=sbase:
			d=os.path.join(sdir,dbase)
			saferename(s,d)
	else:
		raise "err:tag:%s,%s,%s,%s"%(repr(s),repr(ta),repr(tt),repr(tn))

def renum(forcetpos):
	l=[i for i in os.listdir('.') if i.lower().endswith('.mp3')]
	# find max
	m={}
	for i in l:
		mo=re.search("([0-9]+)",i)
		if mo:
			tpos,num=divmod(int(mo.group(1)),100)
			if forcetpos:
				tpos=forcetpos
			m[tpos]=max(m.get(tpos,0),num)
	# tag track
	for i in l:
		mo=re.search("([0-9]+)",i)
		if mo:
			tag=eyeD3.Tag()
			tag.link(i)
			tpos,num=divmod(int(mo.group(1)),100)
			if forcetpos:
				tpos=forcetpos
			tmax=m[tpos]
			if tpos:
				tpos_frame=tag.frames["TPOS"]
				if not tpos_frame:
#				if 1:
					tag.setTextFrame("TPOS", str(tpos));
					tag.update()
			tn=tag.getTrackNum()
			if (not tn[0]) or (not tn[1]):
				tag.setTrackNum((num,tmax))
				tag.update()
		print i,tn,num,tmax

def replace(s,d):
	l=[i for i in os.listdir('.') if i.lower().endswith('.mp3')]
	for i in l:
		saferename(i,i.replace(s,d))

def track():
	l=[i for i in os.listdir('.') if i.lower().endswith('.mp3')]
	for i in l:
		tag=eyeD3.Tag()
		tag.link(i, eyeD3.ID3_V1)
		tn=tag.getTrackNum()[0]
		print i,tn
		tag.link(i)
		tag.setTextFrame("TRCK", str(tn))
		tag.update()

if len(sys.argv)==2 and sys.argv[1]=="rename":
	files=os.popen("find . -iname \\*.mp3").read().split("\n")[:-1]
	files.sort()
	#files=files[:20]
	for i in files:
		renamefile(i)
elif len(sys.argv)==2 and (sys.argv[1]=="mkdir"):
	for i in os.listdir("."):
		if i.find("_-_")!=-1:
			l=i.split("_-_")
			n=l[0]
			try:
				os.mkdir("../"+n)
			except:
				pass
elif len(sys.argv)==2 and (sys.argv[1]=="renum"):
	renum(0)
elif len(sys.argv)==2 and sys.argv[1].startswith("renum"):
	c=sys.argv[1]
	a=int(c[len("renum"):])
	renum(a)
elif len(sys.argv)==4 and (sys.argv[1]=="replace"):
	replace(sys.argv[2],sys.argv[3])
elif len(sys.argv)==2 and (sys.argv[1]=="track"):
	track()
else:
	print "usage: rename,renum,replace s d"

"""
 tag.link("/some/file.mp3")
 print tag.getArtist()
 print tag.getAlbum()
 print tag.getTitle()

Read an mp3 file (track length, bitrate, etc.) and access it's tag:
  if eyeD3.isMp3File(f):
     audioFile = eyeD3.Mp3AudioFile(f, self.opts.tagVersion)
     tag = audioFile.getTag()

Specific tag versions can be selected:
     tag.link("/some/file.mp3", eyeD3.ID3_V2)
     tag.link("/some/file.mp3", eyeD3.ID3_V1)
     tag.link("/some/file.mp3", eyeD3.ID3_ANY)  # The default.

Or you can iterate over the raw frames:
     tag = eyeD3.Tag()
     tag.link("/some/file.mp3")
     for frame in tag.frames:
        print frame

Once a tag is linked to a file it can be modified and saved:
     tag.setArtist(u"Cro-Mags")
     tag.setAlbulm(u"Age of Quarrel")
     tag.update()

If the tag linked in was v2 and you'd like to save it as v1:
     tag.update(eyeD3.ID3_V1_1)

Read in a tag and remove it from the file:
     tag.link("/some/file.mp3")
     tag.remove()
-----------------------------------------------------------
rename_DIR_ALL.sh
#!/bin/zsh
for I in *(/); do
	./rename_DIR_AL_ONE.sh "$I"
done;
-----------------------------------------------------------
rename_DIR_AL_ONE.sh
#!/bin/sh
if [ "$1" ]; then
	A="$1"
else
	exit 0;
fi
D=$(basename "$1");
echo "$D"
for I in "$D"/*.mp3; do
	NAME=$(id3 -l "$I" | grep Album | cut -d: -f2 | sed -e 's/Year$//' | sed -e 's/^ *//' | sed -e 's/ *$//'| sed -e 's/ /_/g')
	echo "$NAME"
done;
NEWNAME="${D}_-_$NAME"
mv -i -v "$D" "$NEWNAME"
cd "$NEWNAME";
../rename_albums_one.pl *.mp3
cd ..
-----------------------------------------------------------
rename_albums_one.pl
#!/usr/bin/perl
for($i=0;$i<=$#ARGV;$i++)
{
	print $i;
	$nbr = $f = $ARGV[$i];
	$nbr =~ s/^.*?(\d{1,2})\D.*/$1/;
	print "$f --> got nbr $nbr\n";
	system("id3","-T",$nbr,$f);
	system("id3ren","-template=\%n-\%s.mp3","-repchar"," _+_'_\"_&_",$f);
#	system("id3ren","-template=\%a_-_\%s.mp3","-repchar"," _+_'_\"_&_",$f);
}
-----------------------------------------------------------
rename_albums_two.pl
#!/usr/bin/perl
for($i=0;$i<=$#ARGV;$i++)
{
	$nbr = $n1 = $f = $ARGV[$i];
	$nbr =~ s/^.*?(\d{1,2})\D.*?(\d{1,2})\D.*/$2/;
	$n1 =~ s/^.*?(\d{1,2})\D.*/$1/;
	print "$i -- $f -- got n1 = $1, nbr = $nbr\n";
	system("id3","-T",$nbr,$f);
	system("id3ren","-template=$n1\%n-\%s.mp3","-repchar"," _+_'_\"_&_",$f);
#	system("id3ren","-template=\%a_-_\%s.mp3","-repchar"," _+_'_\"_&_",$f);
}
-----------------------------------------------------------
rename_as_basedir.sh
#!/bin/sh
A=$(pwd)
echo basename $A
B=`basename $A`
echo $B
for I in *; do
	mv -v -i $I ${B}_-_$I;
done;
-----------------------------------------------------------
rename_tagger.pl
#!/usr/bin/perl
for($i=0;$i<=$#ARGV;$i++)
{
	print $i;
	$nbr = $f = $ARGV[$i];
#	$nbr =~ s/^.*?(\d{1,2})\D.*/$1/;
#	print "$f --> got nbr $nbr\n";
#	system("id3","-T",$nbr,$f);
	system("id3ren","-template=\%n-\%s.mp3","-repchar"," _+_'_\"_&_",$f);
#	system("id3ren","-template=\%a_-_\%s.mp3","-repchar"," _+_'_\"_&_",$f);
}
-----------------------------------------------------------
rename_various.pl
#!/usr/bin/perl
for($i=0;$i<=$#ARGV;$i++)
{
	print $i;
	$nbr = $f = $ARGV[$i];
	$nbr =~ s/^.*?(\d{1,2})\D.*/$1/;
	print "$f --> got nbr $nbr\n";
	system("id3","-T",$nbr,$f);
#	system("id3ren","-template=\%n-\%t_-_\%a_-_\%s.mp3","-repchar"," _+_'_\"_&_",$f);
	system("id3ren","-template=\%a_-_\%s.mp3","-repchar"," _+_'_\"_&_",$f);
}
sub maketree {
	my (@dirnames,$tmp,$i,$j);
	opendir (DIR,"."); @dirnames = readdir(DIR); closedir (DIR);
    foreach $tmp (@dirnames) {
		$i = $tmp;
		if ( -f "$i" ) {
			$o = $i;
			$o =~ s/ /_/g;
			$o =~ s/!/_/g;
			$o =~ s/\&/and/g;
			$o =~ s/\(/_/g;
			$o =~ s/\)/_/g;
			$o =~ s/\{/_/g;
			$o =~ s/\}/_/g;
			$o =~ s/'/_/g;
			$o =~ s/,/_/g;
			if ($i ne $o) {
			print "file is $i $o\n";	
				rename($i,$o);
			}
		}
		if ( (-d "$i") and ($tmp ne ".") and ($tmp ne "..") ) {
#			print(" in " .  `pwd` ) ;
			$o = $i;
			$o =~ s/ /_/g;
			$o =~ s/!/_/g;
			$o =~ s/\&/and/g;
			$o =~ s/\(/_/g;
			$o =~ s/\)/_/g;
			$o =~ s/\{/_/g;
			$o =~ s/\}/_/g;
			$o =~ s/'/_/g;
			$o =~ s/,/_/g;
			if ($i ne $o) {
				print("mv $i $o\n");
				rename($i,$o);
			}
 			chdir $o;
# 			chdir $i;
			&maketree;
			chdir "..";
		}
	}
}

&maketree(".");

"""

