#!/usr/bin/python

# Note on 2012-06-11
#     I'm not maintaining this script because I don't use it any more.
#     audacious2 works fine for me without wrapping.

# The version of audacious that I have installed isn't very intelligent about
# dealing with a list of files provided on the command line. I didn't want to
# use audtool; I was happy with how I used to use xmms.
#
# This script wraps audacious and:
#     - each filename is turned into a full path so they will work if audacious
#       is already running and was started in a different directory.
#     - .m3u files are split into an explicit list of files because audacious
#       seems to need playlists to be loaded with a separate GUI-only option.

# BUGS: Some path handling is Unix specific because I was lazy.

import sys, os, os.path

prog = 'audacious'

######################################################################
# I had to add this nasty code due to a regression in recent audacious
# I have 1.5.1, I don't /think/ this happened in 1.5.0.
# Hopefully I can remove this bit at some point. Someone has a patch:
# http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=491043
######################################################################
def prod_audacious():
    """Bypass a bug where audacious no longer looks at files unless an
    audacious is already running"""
    from subprocess import Popen, PIPE
    output = Popen(["ps", "-C", prog], stdout=PIPE).communicate()[0]
    number_of_audaciouses = len(output.strip().split('\n')) - 1
    if number_of_audaciouses < 1:
        Popen([prog])
        # Don't continue until audacious is communicative
        output = ''
        while not output:
            output = Popen(["audtool", "version"], \
                    stdout=PIPE).communicate()[0]
prod_audacious()
######################################################################

def m3u_proc(filename):
    """If filename is a .m3u file then return a list with its filenames.
    
    Otherwise return a list containing just the original filename."""
    if filename[-4:].lower() != '.m3u':
        return [filename]

    base = os.path.dirname(filename)

    files = []
    fid = open(filename, 'r')
    for line in fid.readlines():
        line = line.strip()
        if line[0] == '#':
            continue
        if line[0] == '/':
            files.append(line)
        else:
            files.append(base + '/' + line)
    return files

# Expand filename arguments
new_args = [prog]
options_ended = False
pwd = os.getcwd()
for arg in sys.argv[1:]:
    is_file = (options_ended or (arg[0] != '-'))
    if is_file:
        filename = os.path.abspath(arg)
        files = m3u_proc(filename)
        new_args.extend(files)
    else:
        new_args.append(arg)
    if arg == '--':
        options_ended = True

# Run
os.execvp(prog, new_args)

