#!/usr/bin/env python
# Licensed and redistributable under GPLv3
# Written by David Henningsson <david.henningsson@canonical.com>
# (C) 2010 Canonical Ltd

''' This file takes a "configuration" file as input and gives an
    udev rule file as output, meant for usage with the new (juju)
    firewire stack.
    Suggested name of the output file is 60-ffado.rules
    (after default.rules, before acl.rules) 
'''

import sys
import re

out_header = "\
# Do not edit this file, it will be automatically overwritten on upgrade.\n\
# This list has been auto-generated from the \"configuration\" file in top of libffado's source tree.\n\
SUBSYSTEM!=\"firewire\", GOTO=\"ffado_end\"\n"

out_footer = 'LABEL="ffado_end"\n'
out_row = 'ATTRS{vendor}=="%s", ATTRS{model}=="%s", GROUP="audio", ENV{ID_FFADO}="1" # %s, %s'

i_pattern = re.compile("(\w+)\s*=\s*((\w+)|(\"(.*?)\"))\s*;");
end_pattern = re.compile("[^#]*\}");
start_pattern = re.compile("[^#]*\{");

print out_header
for line in sys.stdin.readlines():
    if start_pattern.search(line):
        d = dict()
        continue
    if end_pattern.search(line):
        # format vendor and model according to sysfs
        vendorid = "0x%06x" % int(d['vendorid'],0)
        modelid = "0x%06x" % int(d['modelid'],0)
        print out_row % (vendorid, modelid, d['vendorname'], d['modelname'])
        continue
    m = i_pattern.search(line)
    if m is not None:
        if m.group(3) is None:
            d[m.group(1)] = m.group(5)
        else:
            d[m.group(1)] = m.group(3)

print out_footer
