#!/usr/bin/python
#
# Copyright (C) 2009 Jan Essert
#
# This script invokes mp3gain recursively
#
# It assumes that your MP3s are sorted as follows:
#
# initial/artist/single_song.mp3
# initial/artist/album/song.mp3
#
# where initial is the first letter of the artist
#
# 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 2, 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, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA

import os,sys,subprocess

basedir = sys.argv[1]

print("Crawling directory "+basedir+"\n")

if len(sys.argv!=1):
    print("""Usage: ./calculate_gain_for_initial_foldes.py [folder]
    
    The script assumes that your MP3s are sorted as follows:
    
    folder/initial/artist/single_song.mp3
    folder/initial/artist/album/song.mp3
    
    where initial is the first letter of the artist.""")

initial_list = os.listdir(basedir)
initial_list.sort()
for initial in initial_list:
    if not os.path.isdir(os.path.join(basedir,initial)):
        continue
    if initial=="iTunes":
        continue
    artist_list = os.listdir(os.path.join(basedir,initial))
    artist_list.sort()
    for artist in artist_list:
        artist_path = os.path.join(os.path.join(basedir,initial),artist)
        if not os.path.isdir(artist_path):
            continue
        print("Artist: "+artist)
        albums_and_single_songs = os.listdir(artist_path)
        albums_and_single_songs.sort()
        there_are_single_songs = False
        for entry in albums_and_single_songs:
            albumpath = os.path.join(artist_path,entry)
            if os.path.isdir(albumpath):
                print("Tagging album "+entry)
                filelist = [os.path.join(albumpath,file) for file in os.listdir(albumpath) if ".mp3" in file]
                filelist.sort()
                output=subprocess.Popen(["mp3gain","-a","-k","-p"]+filelist,stdout=subprocess.PIPE).communicate()[0]
                print(output)
            elif ".mp3" in entry:
                there_are_single_songs=True
        if there_are_single_songs:
            print("Tagging single songs")
            filelist = [os.path.join(artist_path,file) for file in os.listdir(artist_path) if ".mp3" in file]
            filelist.sort()
            output=subprocess.Popen(["mp3gain","-r","-k","-p"]+filelist,stdout=subprocess.PIPE).communicate()[0]
            print(output)
