#!/usr/bin/env python

# Aurelien Bompard
# gauret(a)free.fr
# Recurse through your amaroK collection and copies the
# cover images in the album's directory
#
# License: GPL


import md5
import commands
import os
import sys
import shutil

import distutils.sysconfig
if distutils.sysconfig.get_python_version() < 2.3:
    print "Python >= 2.3 is required. Please upgrade"
    sys.exit(1)

from optparse import OptionParser
# Argument parsing
usage = "usage: %prog [-d] [-c <cover_filename>]"
parser = OptionParser(usage)
parser.add_option("-d", action="store_true", dest="debug", default=False,
                        help="Debug mode: only show what will be done")
parser.add_option("-c", "--cover-filename", dest="cover_filename", type="string", metavar="FILENAME",
                  help="The covers will always have this FILENAME. If omitted, the album name will be used.")
(options, args) = parser.parse_args()


# Checks
(status, output) = commands.getstatusoutput("dcop amarok")
if status:
    print "AmaroK must be running. Please launch it and restart this script."
    sys.exit(1)

(status, output) = commands.getstatusoutput("dcop amarok collection")
if status:
    print "You must have amaroK >= 1.2.3 to run this script. Please update."
    sys.exit(1)

cover_dir = os.path.join(os.getenv('HOME'), ".kde/share/apps/amarok/albumcovers/large")
if not os.path.exists(cover_dir):
    print "No covers in amaroK's cover folder"
    sys.exit(0)

#
if options.debug:
    print "Running in debug mode. No change will be done."
    print

def associateResults2(command_output):
    """ Outputs a tuple from the result of a dcop call. Number is the number of output fields """
    output_list = command_output.split("\n")
    results = []
    for i in range(0, len(output_list), 2):
        #print '(%s, %s)' % (output_list[i], output_list[i+1])
        results.append( (output_list[i], output_list[i+1]) )
    return results

def getCoverFilename(album):
    """ Returns the filename for the cover image """
    if options.cover_filename:
        return options.cover_filename
    else:
        return album.replace(" ", "_").replace("/", "")+".png"

def copyCover(source, destination):
    """ Copies the source in the destination and creates a .directory file """
    if not options.debug:
        shutil.copy(source, destination)
        dir_file_path = os.path.join(os.path.dirname(destination), '.directory')
        if not os.path.exists(dir_file_path):
            dir_file = open(dir_file_path, 'w')
            dir_file.write("[Desktop Entry]\nIcon=./%s\n" % os.path.basename(destination))
            dir_file.close()

# MAIN

dcop_artists = commands.getoutput('''dcop amarok collection query "SELECT id, name FROM artist WHERE name != ''"''')
artists = associateResults2(dcop_artists)

for artist_tuple in artists:
    #print "Processing artist: %s..." % artist_tuple[1]
    dcop_albums = commands.getoutput('''dcop amarok collection query "SELECT DISTINCT name, dir FROM tags, album ''' \
                                    +'''WHERE tags.album = album.id AND album.name != '' AND artist = %s"''' % artist_tuple[0])
    if not dcop_albums:
        continue
    albums = associateResults2(dcop_albums)
    for album_tuple in albums:
        #print "    Album: %s..." % album_tuple[0]
        md5sum = md5.new(artist_tuple[1].lower() + album_tuple[0].lower()).hexdigest()
        album_cover = os.path.join(cover_dir, md5sum)
        if os.path.exists(album_cover):
            #print "        Cover Found !"
            do_copy = True
            for file in os.listdir(album_tuple[1]):
                if file[-4:] in [".jpg", ".png", ".gif"]:
                    do_copy = False
            if do_copy:
                cover_filename = getCoverFilename(album_tuple[0])
                destination = os.path.join(album_tuple[1], cover_filename)
                print "Copying cover for album \"%s - %s\" to %s" % (artist_tuple[1], album_tuple[0], destination)
                copyCover( album_cover, destination )
            #else:
                #print "        Cover already copied !"
        



