#!/usr/bin/env python
# -*- coding: utf-8 -*-

import rdflib
import glob
import os
import shutil

lv2 = rdflib.Namespace('http://lv2plug.in/ns/lv2core#')
rdf = rdflib.Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')

# Get the first match for a triple pattern, or throw if no matches
def query(model, s, p, o):
    triples = model.triples([s, p, o])
    for i in triples:
        return i
    raise Exception('Bad LV2 extension data')

def genwscript(manifest):
    dir = os.path.dirname(manifest)
    name = os.path.basename(dir).replace('.lv2', '')

    m = rdflib.ConjunctiveGraph()
    m.parse('file:' + manifest, format='n3')

    try:
        # ?uri a lv2:Specification
        uri = query(m, None, rdf.type, lv2.Specification)[0]
        
        # uri lv2:minorVersion ?minor
        minor = query(m, uri, lv2.minorVersion, None)[2]
        
        # uri lv2:microVersion ?
        micro = query(m, uri, lv2.microVersion, None)[2]
    except:
        return False

    if int(minor) != 0 and int(micro) % 2 == 0:
        print('Packaging %s extension version %s.%s' % (name, minor, micro))

        # Make directory and copy all files to it
        distdir = 'build/spec/lv2-%s-%s.%s' % (name, minor, micro)
        os.mkdir(distdir)
        for f in glob.glob('%s/*.*' % dir):
            shutil.copy(f, '%s/%s' % (distdir, os.path.basename(f)))

        pkgconfig_name = str(uri).replace('http://', 'lv2-').replace('/', '-')

        # Generate wscript
        wscript_template = open('wscript.template')
        wscript = open('%s/wscript' % distdir, 'w')
        for l in wscript_template:
            wscript.write(l.replace(
                    '@NAME@', name).replace(
                    '@URI@', str(uri)).replace(
                    '@MINOR@', minor).replace(
                    '@MICRO@', micro).replace(
                    '@PKGCONFIG_NAME@', pkgconfig_name))
        wscript_template.close()
        wscript.close()

        # Generate pkgconfig file
        pkgconfig_template = open('ext.pc.template', 'r')
        pkgconfig = open('%s/%s.pc.in' % (distdir, pkgconfig_name), 'w')
        for l in pkgconfig_template:
            pkgconfig.write(l.replace(
                    '@NAME@', 'LV2 ' + name.title()).replace(
                    '@DESCRIPTION@', 'The LV2 "' + name + '" extension').replace(
                    '@VERSION@', '%s.%s' % (minor, micro)).replace(
                    '@INCLUDE_PATH@', str(uri).replace('http://', 'lv2/')))
        pkgconfig_template.close()
        pkgconfig.close()

        try:
            os.remove('%s/waf' % distdir)
        except:
            pass
        os.symlink('../../../waf', '%s/waf' % distdir)

        olddir = os.getcwd()
        os.chdir(distdir + '/..')
        os.system('tar --exclude=".*" -cjhf %s.tar.bz2 %s' % (
                os.path.basename(distdir), os.path.basename(distdir)))
        os.chdir(olddir)

    return True

@@ -320,17 +320,16 @@
     
-triples =
+for i in
  mod
@@ -353,29 +353,8 @@
  o%5D)
-%0A    for i in triples
 :%0A  
@@ -581,18 +581,8 @@
 rse(
-'file:' + 
 mani
@@ -622,46 +622,13 @@
     
-# ?
 uri 
-a lv2:Specification%0A        uri
+ 
  = q
@@ -677,55 +677,8 @@
 %5B0%5D%0A
-        %0A        # uri lv2:minorVersion ?minor%0A
     
@@ -734,50 +734,8 @@
 %5B2%5D%0A
-        %0A        # uri lv2:microVersion ?%0A
     
@@ -1296,131 +1296,142 @@
     
-# Generate wscript%0A        wscript_template = open('wscript.template')%0A        wscript = open('%25s/wscript' %25 distdir
+def subst_file(source_path, target_path):%0A            source = open(source_path, 'r')%0A            target = open(target_path
 , 'w')%0A
+    
     
@@ -1443,31 +1443,21 @@
 or l in 
-wscript_templat
+sourc
 e:%0A     
@@ -1463,22 +1463,25 @@
         
-wscrip
+    targe
 t.write(
@@ -1515,69 +1515,146 @@
     
-'@NAME@', name).replace(%0A                    '@URI@', str(uri
+    '@DESCRIPTION@', 'LV2 %22' + name + '%22 extension').replace(%0A                        '@INCLUDE_PATH@', str(uri).replace('http://', 'lv2/'
 )).r
@@ -1685,24 +1685,28 @@
     
+    
 '@MI
-NOR
+CRO
 @', mi
-nor
+cro
 ).re
@@ -1732,32 +1732,36 @@
         
+    
 '@MI
-CRO
+NOR
 @', mi
-cro
+nor
 ).replac
@@ -1787,77 +1787,36 @@
     
-'@PKGCONFIG_NAME@', pkgconfig_name))%0A        wscript_template.clos
+    '@NAME@', name).replac
 e(
-)
 %0A   
@@ -1824,409 +1824,238 @@
     
-wscript.close()%0A%0A        # Generate pkgconfig file%0A        pkgconfig_template = open('ext.pc.template', 'r')%0A        pkgconfig = open('%25s/%25s.pc.in' %25 (distdir, pkgconfig_name), 'w')%0A        for l in pkgconfig_template:%0A            pkgconfig.write(l.replace(%0A                    '@NAME@', 'LV2 ' + name.title()).replace(%0A                    '@DESCRIPTION@', 'The LV2 %22' + name + '%22 extension').replac
+                '@PKGCONFIG_NAME@', pkgconfig_name).replace(%0A                        '@URI@', str(uri)).replace(%0A                        '@VERSION@', '%25s.%25s' %25 (minor, micro)))%0A            source.close()%0A            target.clos
 e(
+)
 %0A   
@@ -2059,32 +2059,33 @@
             
+%0A
         
 '@VERSION@',
@@ -2076,174 +2076,188 @@
     
-'@VERSION@', '%25s.%25s' %25 (minor, micro)).replace(%0A                    '@INCLUDE_PATH@', str(uri).replace('http://', 'lv2/')))%0A        pkgconfig_template.close()%0A       
+# Generate wscript%0A        subst_file('wscript.template', '%25s/wscript' %25 distdir)%0A%0A        # Generate pkgconfig file%0A        subst_file('ext.pc.template', '%25s/%25s.pc.in' %25 (distdir,
  pkg
@@ -2262,23 +2262,22 @@
 kgconfig
-.close(
+_name)
 )%0A%0A     

Clean up code.