#!/usr/bin/python
#
# Copyright (C) 2009 Jan Essert
#
# This script invokes mp3gain recursively
#
# It assumes that your MP3s are sorted as follows:
#
# artist/single_song.mp3
# artist/album/song.mp3
#
# 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

if len(sys.argv!=1):
    print("""Usage: ./calculate_gain_all_in_one_folder.py [folder]
    
    The script assumes that your MP3s are sorted as follows:
    
    folder/artist/single_song.mp3
    folder/artist/album/song.mp3""")

initial = sys.argv[1]

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

artist_list = os.listdir(initial)
artist_list.sort()
for artist in artist_list:
    artist_path = os.path.join(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)
