#!/usr/bin/env python

# This script generates override files for ladspa plugins.  The following types
# of entries are generated:
#  - ignore when plugin has different number of inputs to outputs

# The analyseplugin binary (part of ladspa SDK) is required on your path

# usage:
#  mkoverride libs...

import re
import os
import sys
import os.path

def processLibrary(lib):
    '''Analyse plugin library `lib` and return list of tuples, one for each
    plugin in the library.  The tuple contains:
      (lib filename, plugin name, plugin label, id,
      list of inputs, list of outputs, list of controls)
      '''

    p = os.popen('analyseplugin %s' % lib)

    plugins = []

    pluginName = ''
    pluginLabel = ''
    pluginID = ''
    inputPorts = []
    outputPorts = []
    controlPorts = []

    inPorts = False
    for l in p:

        m = re.match(r'^Plugin Name: "(.*)"', l)
        if m:
            pluginName = m.group(1)

        m = re.match(r'^Plugin Label: "(.*)"', l)
        if m:
            pluginLabel = m.group(1)

        m = re.match(r'^Plugin Unique ID: (.*)', l)
        if m:
            pluginID = m.group(1)

        m = re.match(r'^Ports:.*', l)
        if m:
            inPorts = True

        if inPorts:
            m = re.match(r'^(?:Ports:)?\s+"(.*)" input, audio', l)
            if m:
                inputPorts.append(m.group(1))

            m = re.match(r'^(?:Ports:)?\s+"(.*)" output, audio', l)
            if m:
                outputPorts.append(m.group(1))

            m = re.match(r'^(?:Ports:)?\s+"(.*)" input, control', l)
            if m:
                controlPorts.append(m.group(1))

        m = re.match(r'^\s*$', l)
        if m:
            if pluginName != '':
                plugins.append((lib, pluginName, pluginLabel, pluginID,
                                inputPorts, outputPorts, controlPorts))
            pluginName = ''
            pluginLabel = ''
            pluginID = ''
            inputPorts = []
            outputPorts = []
            controlPorts = []

    p.close()

    return plugins


def generateXML(plugins):
    print '<ladspapackage>'

    for p in plugins:
        attrs = []
        elements = []

        # ignore plugins that change the number of channels
        if len(p[4]) != len(p[5]):
            attrs.append('ignore="yes"')

#         if attrs != [] or elements != []:
        if True:
            attrs = [ 'id="%s"' % p[3]] + attrs # prepend ID

            # comment line
            print '  <!-- %s[%s]: %s -->' % (os.path.split(p[0])[1], p[2], p[1])
            print '  <plugin %s>' % '\n          '.join(attrs)
            # TODO: elements
            print '  </plugin>'

    print '</ladspapackage>'


plugins = []
for l in sys.argv[1:]:
    plugins += processLibrary(l)

generateXML(plugins)
